正则表达式匹配项缺少一项? [英] Regex matches missing one match?

查看:94
本文介绍了正则表达式匹配项缺少一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有正则表达式 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中使用lookbehinds,足以仅使用一次前瞻来防止重叠:

Because you cannot use lookbehinds in JavaScript, it is enough to only use one lookahead, to prevent the overlapping:

1(0*)(?=1)

实时示例

并提示您 regex101 示例:您没有添加全局标志,这可以防止一种选择。

这篇关于正则表达式匹配项缺少一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆