Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a pattern with Regex in C#, for the regex challenged?

Tags:

c#

regex

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!

like image 639
Gup3rSuR4c Avatar asked Jan 30 '26 23:01

Gup3rSuR4c


1 Answers

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;
}
like image 175
Daniel Hilgarth Avatar answered Feb 01 '26 13:02

Daniel Hilgarth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!