简体   繁体   中英

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

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!

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;
}

一个解决方案展望未来,看后面,不需要使用组..

(?<={)[^}]*(?=})

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