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](?=[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;
//...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With