bublegumm
bublegumm

Reputation: 315

Regex to match after specific characters

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?

Upvotes: 7

Views: 14926

Answers (3)

Kent
Kent

Reputation: 195069

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.

Upvotes: 10

TDaver
TDaver

Reputation: 7264

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;
   //...
}

Upvotes: 10

marcoaoteixeira
marcoaoteixeira

Reputation: 505

maybe you can try this...

var match = Regex.Match(item, @"!(\w+)");

then get the match.Groups[1].Value

Upvotes: 2

Related Questions