Regex to match 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); 

Matches will have β€œFields! Metadata1” while I need to get β€œMetadata1”

What should I change?

+4
source share
3 answers

don't know C # syntax, for regular expression try:

 (?<=Fields!)\w* 

EDIT add a short explanation:

(?<=foo)bar matches bar only if bar matches foo (foo is not collected as a result of the match) (?<=..) - positive appearance, statement with zero width. google it for details.

+7
source

What you need is called lookbehind / lookahead . Regex has this function , you can specify what follows (or in this case precedes) the current associated string.

[0-9](?=[az]) will match any one digit followed by a lowercase letter.
[0-9](?![az]) will match any single NOT digit followed by a lowercase letter. (this is called a negative look)
(?<=[az])[0-9] will match any one digit preceding the lowercase letter.
(?<![az])[0-9] will match any one NOT digit preceding the lowercase letter (this is called a negative lookbehind)

With this in mind, you want the C # expression:

 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 useful for you if you DO NOT want to match "Fields!". part. A slightly different task if you want to match it, but you also need the meaning of the second part. In this case, I recommend using group names that will capture everything, but you can get some from the group collection. The regular expression in this case would be: Fields!(?'fieldName'\w+) , and using C #

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

maybe you can try this ...

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

then we get match.Groups [1] .Value

+2
source

All Articles