2014-05-15 177 views
-2

我找不到正则表达式<#anystring#>?如何匹配Regex中特定模式的所有匹配项?

例:<#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); 
      } 
     } 
+0

“<#[^<#]+#>”这仅输出第一次出现。其实我不擅长正则表达式。刚刚开始。 – Carlos

+0

如果您有其他信息,请编辑您的问题。你的正则表达式看起来不错,所以这是你如何调用你的正则表达式并处理结果的问题。显示你的C#代码(通过编辑你的问题!) – stema

+0

@卡洛斯更好,所以现在你的问题变得明显。请显示你使用正则表达式的代码,你可能只需要调整一些选项。 – James

回答

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

谢谢。正如我所说,我真的在正则表达式新。 20分钟前开始。谢谢。 – Carlos

0

试试这个,它应该工作

修订

<#(.*?)#>

  • 的点是,除了新行(\ n)的任何字符。
  • *表示0或更多。
  • The?被用来使其不合格。

source here

+0

它没有工作。仍然只给出第一次出现.. – Carlos

+0

我更新了括号应该现在工作 – mosaad

+0

你见过编辑的问题?这不是使用正则表达式的问题。 – stema