简体   繁体   中英

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?

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](?=[az]) will match any one digit followed by a lowercase letter.
[0-9](?![az]) will match any one digit NOT followed by a lowercase letter. (this is called a negative lookahead)
(?<=[az])[0-9] will match any one digit preceeded by a lowercase letter.
(?<![az])[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;
   //...
}

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.

maybe you can try this...

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

then get the match.Groups[1].Value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM