如何匹配正则表达式中特定模式的所有出现?

问题描述 投票:-2回答:2

我找不到<#anystring#>的正则表达式?

例如:<#sda#>或<#32dwdwwd#>或<#和#>之间的任何字符串

我试过"<#[^<#]+#>",但这只输出了第一次。

        string sample = "\n\n<#sample01#> jus some words <#sample02#> <#sample03#> just some words ";
        Match match = Regex.Match(sample, "<#[^<#]+#>");
        if (match.Success)
        {
            foreach (Capture capture in match.Captures)
            {
                Console.WriteLine(capture.Value);
            }
        }
c# regex
2个回答
2
投票

您正在使用match()方法。尝试阅读documentation,你会看到它只返回第一场比赛。

尝试使用matches()方法,它返回一个MatchCollection

它看起来像这样(小心,没有在这里直接编写测试)

string sample = "\n\n<#sample01#> jus some words <#sample02#> <#sample03#> just some words ";
    MatchCollection mc = Regex.Matches(sample, "<#(.*?)#>");
    foreach (Match m in mc)
        {
            Console.WriteLine(m.Groups[0]);
        }
    }

0
投票

尝试这个,它应该工作

更新

<#(.*?)#>

  • 点是除新行(\ n)之外的任何字符。
  • *表示0或更多。
  • 的?用来使它不合适。

source here

© www.soinside.com 2019 - 2024. All rights reserved.