Reputation: 9490
Taking the following string example, what is the pattern I should use to extract all of the string instances I need? So, taking:
string Text = @"Dear {Customer.Name},
Lorem ipsum dolor sit amet, {Customer.FirstName}";
And extracting {Customer.Name}
and {Customer.FirstName}
? As a bonus can the {
and }
be removed during the extraction?
I'm poking around with LinqPad, and I've got new Regex("{[A-Za-z0-9.]+}", RegexOptions.Multiline).Match(Text)
so far, but it's only matching the first substring of {Customer.Name}
.
I'm very challenged in regular expressions, so I'd appreciate detailed help.
Thanks in advance!
Upvotes: 2
Views: 358
Reputation: 174299
Your regex looks fine. The only problem is, that you need to call Matches
instead of Match
to get all matches in the input string.
You can put the part you want to have as a result in a sub group and then use only the sub group in further processing:
var matches = Regex.Matches(Text, "{([A-Za-z0-9.]+)}", RegexOptions.Multiline);
foreach(Match match in matches)
{
var variable = match.Groups[1].Value;
}
Upvotes: 7
Reputation: 21300
a solution look ahead and look behind, no need to use group..
(?<={)[^}]*(?=})
Upvotes: 2