C# 正则表达式实例即使存在,也找不到多个匹配项
我在使用Regex,我写了以下内容:C# 正则表达式实例即使存在,也找不到多个匹配项,c#,regex,C#,Regex,我在使用Regex,我写了以下内容: 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.Matc
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方法应该同时找到“nn”和“na”。然而,它只找到了“n”,我不明白这是为什么。正则表达式机器只匹配一个,如果您想要更多,您必须在第一次匹配后自己重新启动它。您有两个问题:
1) 你把火柴锚定在绳子的末端。所以实际上,匹配的值是“n…a”,而不是“n…n”
2) 中间的“n”被第一场比赛消耗,因此不能成为第二场比赛的一部分。如果您将“n”更改为“nx”(并删除$),您将看到“n…n”和“x…a”
简短但完整的示例:
using System;
using System.Text.RegularExpressions;
public class Test
{
static void Main(string[] args)
{
string text = "ignored a bc d";
Regex regex = new Regex(@"[a-z][\s]{4,}[a-z]");
foreach (Match match in regex.Matches(text))
{
Console.WriteLine(match);
}
}
}
结果:
a b
c d
正则表达式中的
$
表示模式必须出现在行尾。如果要查找所有长空格,此简单表达式就足够了:
\s{4,}
如果您真的需要知道空间是否由a-z包围,您可以这样搜索
(?<=[a-z])\s{4,}(?=[a-z])
(?我就是不明白为什么…
我认为第一次匹配使用的“为什么”是为了防止类似“\\w+s”
这样的正则表达式,该正则表达式的目的是让以“s”结尾的每个单词在与“cats”匹配时返回“ts”、“ats”和“cats”.否:regex.Matches
生成所有匹配项。regex在其第一个匹配项中使用第二个n
。匹配项不能重叠。在regex找到匹配项后,它会在该匹配项后继续搜索。这与查找(Ctrl/F)的行为相同在VS或MS Word或几乎任何其他文本编辑器中运行。@Oliver-确切地说,我的答案可能更适合作为Jon帖子的评论。但我还没有这方面的代表。是的(+1)——环顾断言是解决这类问题的关键,因为当引擎从左到右遍历字符串时,它们不会“消耗”字符。
(?<=prefix)find(?=suffix)