簡體   English   中英

正則表達式不匹配具有 10 個連續數字的字符串。 數字可以用空格分隔。 所有其他字符串返回匹配項

[英]Regex to NOT match a string with 10 consecutive digits. The digits may be separated by white space. All other string return a match

我有一個通過 5/7 單元測試的 codepen。 卡在以非數字字符開頭的字符串上。

https://codepen.io/david-grieve/pen/pBpGoO?editors=0012

var regexString = /^\D*(?!(\s*\d\s*){10,}).*/;

 var regexString = /^\\D*(?!(\\s*\\d\\s*){10,}).*/; var tests = [{ text: 'abc123', ismatch: true }, { text: '1234567890', ismatch: false }, { text: '123456789', ismatch: true }, { text: 'abc1234567890efg', ismatch: false }, { text: '123 456 789 123', ismatch: false }, { text: 'abc1234567890', ismatch: false }, { text: '1234567890efg', ismatch: false } ]; console.log(new Date().toString()); tests.map(test => console.log(test.text, regexString.test(test.text) == test.ismatch));

使用此正則表達式,以下字符串通過單元測試

  • “abc123”真
  • “1234567890”是真的
  • “123456789”是真的
  • “123 456 789 123”真
  • “1234567890efg”是真的

這些未通過單元測試

  • “abc1234567890”假
  • “abc1234567890efg”假

注意: /^\\D{3,}(?!(\\s*\\d\\s*){10,}).*/ 通過了所有的測試,但顯然是錯誤的。

^\\D*(?!的問題在於,即使在負前瞻中發現了一個長數字/空格字符串,一旦負前瞻匹配, \\D匹配的部分將簡單地回溯一個字符。例如,當

^\D*(?!\d{10,}).*

火柴

abc1234567890

\\D*匹配ab ,而.*匹配c1234567890 的之間的位置bc緊跟一個長數/空間子串,所以比賽不會失敗。

另外,因為某些數字可能出現10 個連續數字之前,所以開頭的^\\D*是不夠的 - 例如,如果輸入是1a01234567890呢? 相反,嘗試

^(?!.*(\d\s*){10}).*

這可以確保每個位置后面都沒有(10 位數字,可能用空格分隔)。

https://regex101.com/r/v7t4IC/1

如果數字只能出現在字符串中的單個塊中(可能用空格分隔),那么如果您處於支持所有格量詞的環境中,您的模式就會起作用,從而防止回溯,例如:

^\D*+(?!(\s*\d\s*){10,}).*
    ^

https://regex101.com/r/eGdw2l/1

(但不幸的是,Javascript 不支持這種語法)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM