Skip to main content
 首页 » 编程设计

c#之正则表达式实例即使存在也找不到多个匹配项

2024年01月01日45lovecherry

我正在使用正则表达式,我写了这个:

 static void Main(string[] args) 
    { 
        string test = "this a string meant to test long space recognition      n       a"; 
        Regex regex = new Regex(@"[a-z][\s]{4,}[a-z]$"); 
        MatchCollection matches = regex.Matches(test); 
        if (matches.Count > 1) 
            Console.WriteLine("yes"); 
        else 
        { 
            Console.WriteLine("no"); 
            Console.WriteLine("the number of matches is "+matches.Count); 
        } 
    } 

在我看来,Matches 方法应该同时找到“n n”和“n a”。然而,它只能找到“n n”,我只是不明白为什么会这样......

请您参考如下方法:

正则表达式中的 $ 表示模式必须出现在行尾。如果你想找到所有的长空格,这个简单的表达式就足够了:

\s{4,} 

如果你真的需要知道空格是否被a-z包围,你可以这样搜索

(?<=[a-z])\s{4,}(?=[a-z]) 

这使用模式...

(?<=prefix)find(?=suffix) 

...并查找包含在前缀和后缀之间的位置。前缀和后缀不是匹配的一部分,即 match.Value 仅包含连续的空格。因此,您不会遇到 Jon Skeet 提到的 “n” is consumed 问题。