Skip to main content
 首页 » 编程设计

c#之正则表达式:为什么每个找到的项目都没有组

2024年02月03日28JustinYoung

我有以下文字:

<i><b>It is noticeably faster.</b></i> <i><b>They take less disk space.</i> 

以及以下正则表达式:

(</[b|i|u]>)+(\s*)(<[b|i|u]>)+ 

匹配创建以下组:

0: </b></i>   <b><i> 
1: </i> 
2: spaces 
3: <b> 

我如何更改我的正则表达式以创建这样的组:

0: </b></i>   <b><i> 
1: </b> 
2: </i> 
3: spaces 
4: <i> 
3: <b> 

请您参考如下方法:

我怀疑您已经得到了所需的东西 - 您只需要枚举每个组的捕获。这是一个示例程序,显示了实际操作:

using System; 
using System.Text.RegularExpressions; 
 
class Test 
{ 
    static void Main() 
    { 
        string text =  
"<i><b>It is noticeably faster.</b></i> <i><b>They take less disk space.</i>"; 
        Regex pattern = new Regex(@"(</[b|i|u]>)+(\s*)(<[b|i|u]>)+"); 
 
        Match match = pattern.Match(text); 
        foreach (Group group in match.Groups) 
        { 
            Console.WriteLine("Next group:"); 
            foreach (Capture capture in group.Captures) 
            { 
                Console.WriteLine("  " + capture.Value); 
            } 
        } 
    } 
}