在C#中获取重叠的正则表达式匹配 [英] Getting overlapping regex matches in C#
问题描述
我有正则表达式 1(0 *)1
和测试字符串 1000010001
I have the regex 1(0*)1
and the test string 1000010001
我想进行2场比赛,但是我发现只有1场比赛:
I want to have 2 matches, but I find that only 1 gets found :
var regex = new Regex("1(0*)1");
var values = regex.Matches(intBinaryString);
// values only has 1 match
regexonline似乎同意: https://regex101.com/r/3J9Qxj/1
regexonline seems to agree : https://regex101.com/r/3J9Qxj/1
我在做什么错了?
推荐答案
您已经在第一个匹配中选择了第二个零前面的1.
You are already selecting the 1 in front of the second zero by the first match.
100001 0001
^^^^^^
这是第一场比赛.其余的只是 0001
,与您的正则表达式不匹配.
This is the first match. The rest is just 0001
which does not match your regex.
如果您使用先行/后退,则可以避免这种行为:
You can circumvent this behavior if you are using lookaheads/lookbehinds:
(?<=1)(0*)(?=1)
由于您无法在JavaScript中使用后备导航,仅使用一次前瞻就足以防止重叠:
Because you cannot use lookbehinds in JavaScript, it is enough to only use one lookahead, to prevent the overlapping:
1(0*)(?=1)
以及您的 regex101
示例的提示:您没有添加全局标志,这会阻止多个选择.
这篇关于在C#中获取重叠的正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!