匹配所有长度为 n 的连续数字 [英] Match all consecutive numbers of length n
问题描述
在我的例子中 n=4.
Where n=4 in my example.
我对 Regex 很陌生,现在已经搜索了 20 分钟.有一些有用的网站可以简化事情,但我不知道如何继续.
I'm very new to Regex and have searched for 20 minutes now. There are some helpful websites out there that simplify things but I can't work out how to proceed with this.
我希望从中提取 4 个连续数字的每个组合:
I wish to extract every combination of 4 consecutive digits from this:
12345
获得:
1234 - possible with ^\d{4}/g - Starts at the beginning
2345 - possible with \d{4}$/g - Starts at the end
但我不能两者兼得!输入可以是任意长度.
But I can't get both! The input could be any length.
推荐答案
您的表达式没有按预期工作,因为这两个子字符串重叠.
Your expression isn't working as expected because those two sub-strings are overlapping.
除了零长度断言之外,输入字符串中的任何字符都将在匹配过程中被消耗,导致找不到重叠匹配.
Aside from zero-length assertions, any characters in the input string will be consumed in the matching process, which results in the overlapping matches not being found.
您可以通过使用前瞻和捕获组来检索重叠匹配来解决此问题.这是有效的,因为前瞻断言(以及后视断言)被归类为零长度断言,这意味着它们不消耗匹配;从而允许您找到任何重叠的匹配项.
You could work around this by using a lookahead and a capturing group to retrieve the overlapping matches. This works because lookahead assertions (as well as lookbehind assertions) are classified as zero-length assertions, which means that they don't consume the matches; thereby allowing you to find any overlapping matches.
(?=(\d{4}))
这里是一个简短的片段,演示了这一点:
Here is a quick snippet demonstrating this:
var regex = /(?=(\d{4}))/g;
var input = '12345678';
var match;
while ((match = regex.exec(input)) !== null) {
if (match.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log(match[1]);
}
这篇关于匹配所有长度为 n 的连续数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!