正则表达式匹配字符串中的多个子字符串

本文关键字:字符串 正则表达式 | 更新日期: 2023-09-27 18:30:14

所以我有一个字符串,其中包含一个子字符串的多次出现。所有这些字符串都具有以下格式:<c@=someText>Content<c>

例:

This combination of plain text and <c=@flavor> colored text<c> is valid. <c=@warning>Multiple tags are also valid.<c>

我想通过正则表达式提取每个子字符串。但是,如果我使用以下正则表达式<c=@.+?(?=>)>.*<c>它将匹配从第一个<c...到最后一个<c>的所有内容。我想要的是这些子字符串中的每一个作为一个项目。我该怎么做,如果我不能用正则表达式做到这一点,实现我的目标的最佳方式是什么。

正则表达式匹配字符串中的多个子字符串

string input = @"This combination of plain text and <c=@flavor> colored text<c> is valid. <c=@warning>Multiple tags are also valid.<c>";
var matches = Regex.Matches(input, @"<c=@(.+?)>(.+?)<c>")
                .Cast<Match>()
                .Select(m => new
                {
                    Name = m.Groups[1].Value,
                    Value = m.Groups[2].Value
                })
                .ToList();

您可以使用命名捕获组以及前瞻和后瞻来获取"类型"和"文本":

var pattern = @"(?<=<c=@)(?<type>[^>]+)>(?<text>.+?)(?=<c>)";
var str = @"This combination of plain text and <c=@flavor> colored text<c> is valid. <c=@warning>Multiple tags are also valid.<c>";
foreach (Match match in Regex.Matches(str, pattern))
{
   Console.WriteLine(match.Groups["type"].Value);
   Console.WriteLine(match.Groups["text"].Value);
   Console.WriteLine();
}

输出:

flavor
 colored text
warning
Multiple tags are also valid.

模式:

(?<=<c=@) :寻找<c=@

(?<type>[^>]+)> : 抓住一切直到>,称之为type

(?<text>.+?) : 抓住一切,直到展望未来,称之为text

(?=<c>) : 找到<c>时停止