其中n = 4在我的例子中。匹配所有連續數字的長度n
我對Regex很新,現在已經搜索了20分鐘。有一些有用的網站可以簡化事情,但我無法解決如何進行此操作。
我要連續4個數字的每個組合由該提取:
12345
獲得:
1234 - possible with ^\d{4}/g - Starts at the beginning
2345 - possible with \d{4}$/g - Starts at the end
但我不能兩全!輸入可以是任意長度。
其中n = 4在我的例子中。匹配所有連續數字的長度n
我對Regex很新,現在已經搜索了20分鐘。有一些有用的網站可以簡化事情,但我無法解決如何進行此操作。
我要連續4個數字的每個組合由該提取:
12345
獲得:
1234 - possible with ^\d{4}/g - Starts at the beginning
2345 - possible with \d{4}$/g - Starts at the end
但我不能兩全!輸入可以是任意長度。
如預期,因爲這兩個子串是重疊的表達式是行不通的。
除了零長度斷言之外,輸入字符串中的任何字符都將在匹配過程中消耗,導致重疊匹配找不到。
您可以通過使用前瞻和捕獲組來檢索重疊匹配來解決此問題。這是有效的,因爲前瞻斷言(以及後向斷言)被分類爲零長度斷言,這意味着它們不消耗匹配;從而讓你找到任何重疊的比賽。
(?=(\d{4}))
這裏是一個快速片段演示此:
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]);
}
使用前瞻斷言所有的可能性
(?=(0123|1234|2345|3456|4567|5678|6789))
(?=
( # (1 start)
| 1234
| 2345
| 3456
| 4567
| 5678
| 6789
) # (1 end)
)
輸出
** Grp 0 - (pos 0 , len 0) EMPTY
** Grp 1 - (pos 0 , len 4)
1234
------------------
** Grp 0 - (pos 1 , len 0) EMPTY
** Grp 1 - (pos 1 , len 4)
2345
謝謝你的詳細解釋。我只是問[這個問題](http://stackoverflow.com/questions/42456201/what-should-the-javascript-match-regex-function-return),因爲我很難返回比賽。你對零長度的評價已經超出了我的頭腦,但也許可以解釋爲什麼我會得到奇怪的結果。編輯:我應該澄清,我沒有使用你的代碼,因爲它導致無限循環出於某種原因。 – DaveHolt