[英]Regex to match any set of numbers except the 10 digit numbers starting with 7
我想捕獲除以 7 開頭的 10 位數字之外的所有數字(任何數字)。
71234567890 - 應該匹配
7123456789 - 不應該匹配
1234567890- 應該匹配
使用模式
/7\d{9}|(\d+)/
^^^^^^ MATCH 10-DIGIT NUMBER STARTING WITH SEVEN, DO NOT CAPTURE
^ --OR--
^^^^^ MATCH OTHER SEQUENCES OF DIGITS AND DO CAPTURE
這將匹配以 7 開頭的 10 位數字,但不會捕獲它; 否則,它將匹配數字序列並捕獲它。
現在
'7123456789'.match(regexp)
["7123456789", undefined]
'1234567890'.match(regexp)
["1234567890", "1234567890"]
換句話說,捕獲的字符串將在match
返回的數組的第二個元素中找到。
如果要將其錨定到字符串的開頭和結尾,則
/^7\d{9}$|(^\d+$)/
正如評論中所建議的那樣,您也可以通過負面展望來做到這一點,但這里不需要它,對於剛開始使用正則表達式的人來說可能有點麻煩。
(?:(?:^|\D)(7\d{1,8}|7\d{10,})(?:\D|$))
看演示
為了獲得除以“7”開頭的 10 位數字字符串之外的任意數量的數字
你必須對'7'進行特殊處理。 真的沒有辦法解決它。
最快的方法是純正則表達式解決方案,因為引擎留在里面
運行 C++ 引擎代碼並且不與宿主語言交互。
有兩種方式,錨定或中弦。
錨定: ^(?:7(?!\\d{9}$)|[012345689])\\d*$
(數字字符串是整體匹配,即在捕獲組 0 中)
^ # Beginning of string
(?: # Cluster, get first digit
7 # '7'
(?! \d{9} $) # not followed by nine more digits
| # or
[012345689] # Any digit except '7' (i.e. [^\D7])
) # End cluster
\d* # Get optional remaining digits
$
中間字符串: (?:^|\\D)((?:7(?!\\d{9}(?:\\D|$))|[012345689])\\d*)
(數字字符串在捕獲組 1 中)
(?: ^ | \D ) # Beginning of string or not a digit
( # (1 start), The number
(?: # Cluster, get first digit
7 # '7'
(?! # Assertion, not followed by nine more digits
\d{9}
(?: \D | $ ) # (forces no more/less than nine) digits
)
| # or
[012345689] # Any digit except '7' (i.e. [^\D7])
) # End cluster
\d* # Get optional remaining digits
) # (1 end)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.