Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help parsing a string using Regex

Status
Not open for further replies.

jmeckley

Programmer
Jul 15, 2002
5,269
0
0
US
the original string would look something like this
Code:
[anything] FROM '[anything]' value_2_find [anything]
I want to get the value of [tt]value_2_find[/tt]. which may contain alphanumerics and underscores.
this is what I have now, but it returns the entire string
Code:
string substring = Regex.Replace(input, @" FROM '\w+' (\w+) ", "$1");

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
figured it out. 1st, I should be using Match, not Replace. after trail and error I came up with this, which works.
Code:
Match match = Regex.Match(CommandText, @"FROM '(\S+)' (\w+) ");
if (match.Success)
{
   return match.Result("$2");
}
return string.Empty;

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
An alternativre pattern:

[tt](?<=FROM[ ]\S+[ ])\w+[/tt]

then, you just need:

[tt]return match.ToString()[/tt]


The pattern uses a "Positive look behind", meaning only return the desired match if it follows the match in the prefix. In other words, only return:
[tt]\w+[/tt]
if it follows:
[tt]FROM[ ]|S+[ ][/tt]

Hope this helps.

[vampire][bat]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top