Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match after specific characters

Tags:

c#

regex

var str = "=IIF(IsNothing(Fields!Metadata1.Value),"N/A",Fields!Metadata1.Value)";
var regexp = new Regex(@"Fields!(\w+)");
var matches = regexp.Matches(str);

The matches will have "Fields!Metadata1" while I need to get "Metadata1"

What shall I change?

like image 940
bublegumm Avatar asked Feb 22 '13 13:02

bublegumm


2 Answers

What you need is called lookbehind/lookahead. Regex has this feature, you can specify what follows (or in this case preceeds) the currently matched string.

[0-9](?=[a-z]) will match any one digit followed by a lowercase letter.
[0-9](?![a-z]) will match any one digit NOT followed by a lowercase letter. (this is called a negative lookahead)
(?<=[a-z])[0-9] will match any one digit preceeded by a lowercase letter.
(?<![a-z])[0-9] will match any one digit NOT preceeded by a lowercase letter.(this is called a negative lookbehind)

With that in mind, the c# expression you want is:

var str = "=IIF(IsNothing(Fields!Metadata1.Value),"N/A",Fields!Metadata1.Value)";
var regexp = new Regex(@"(?<=Fields!)(\w+)");
var matches = regexp.Matches(str);

EDIT: this is good for you if you DON'T want to match the "Fields!" part. A slightly different task is if you want to match it, but you also need the second part's value. In which case, I recommend using named groups, which will capture the entire thing, but you can get the part from the Groups collection. The regex in that case will be: Fields!(?'fieldName'\w+), and the c# usage is

var str = "=IIF(IsNothing(Fields!Metadata1.Value),"N/A",Fields!Metadata1.Value)";
var regexp = new Regex(@"Fields!(?'fieldName'\w+)");
var matches = regexp.Matches(str);
foreach (Match m in matches) 
{
   var fieldName = m.Groups["fieldName"].Value;
   //...
}
like image 125
TDaver Avatar answered Sep 19 '22 17:09

TDaver


don't know c# syntax, for regex, try:

(?<=Fields!)\w*

EDIT add short explanation:

(?<=foo)bar matches bar only if bar is following foo (foo is not gonna in match result) (?<=..) is positive look behind, zero-width assertion. google it for details.

like image 25
Kent Avatar answered Sep 17 '22 17:09

Kent