【问题标题】:Regex match multiple substrings inside a string正则表达式匹配字符串中的多个子字符串
【发布时间】:2014-11-13 19:16:26
【问题描述】:

所以我有这个字符串,其中包含多次出现的子字符串。所有这些字符串都具有以下格式:<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>

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

【问题讨论】:

  • 删除(?=&gt;),并尝试了解您的模式是如何工作的,您会找到解决方案的。
  • 这可能会有所帮助:stackoverflow.com/questions/4892452/…
  • 你只是想要这些标签内的文字吗?
  • @Jonesy 不,我想要标签内的文本和标签本身。

标签: c# regex string


【解决方案1】:
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();

【讨论】:

  • 这正是我要找的。虽然@Jonesy 也有很好的代码,但你的代码更清晰,没有字符串来选择组。
【解决方案2】:

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

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.

模式:

(?&lt;=&lt;c=@) : 寻找&lt;c=@

(?&lt;type&gt;[^&gt;]+)&gt; : 抓住一切直到&gt;,称它为type

(?&lt;text&gt;.+?) :抓住一切直到前瞻,称之为text

(?=&lt;c&gt;) :找到&lt;c&gt;时停止

【讨论】:

    猜你喜欢
    • 2014-10-11
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多