所以我正在嘗試撰寫一個正則運算式,我想在其中測驗兩件事。該字串僅在以開頭 20且長度在 1 到 5 之間,或者不以 20 開頭但仍應將加號 作為其第一個字符(示例 50)且長度在 1 之間時才有效和 7 那么它也是有效的。這是我為這個驗證寫的:
/^\ (?=20){1,5}|^\ (?!20){1,7}/g
我對其進行了測驗,但它無法正常作業,我不明白為什么。
uj5u.com熱心網友回復:
你所擁有的很接近,但你需要:
.添加要量化的字符選擇器(.可以匹配所有內容)- 約束字串的結尾以防止長度超過最大值
$ - 可以洗掉
g標志,因為您只想要一個匹配項
這給你留下了:
/^\ (?=20).{1,5}$|^\ (?!20).{1,7}$/
你也可以寫成
/^\ ((?=20).{1,5}|(?!20).{1,7})$/
uj5u.com熱心網友回復:
您可以嘗試匹配以下正則運算式:
^\ (?:20(\D.?)?|(?!20(?!\d)).{0,6})$
演示
運算式可以分解如下。
^ # match beginning of string
\ # match ' '
(?: # begin non-capture group
20 # match '20'
(?:\D.?)? # optionally match a non-digit that is optionally
# followed by any character
| # or
(?! # begin negative lookahead
20 # match '20'
(?!\d) # negative lookahead asserts '20' is not followed by a digit
) # end negative lookahead
.{0,6} # match between 0 and 6 characters
) # end non-capture group
$ # match end of string
請注意,' 200'與替換的第二部分匹配(字串不以'20'開頭)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/422162.html
標籤:
下一篇:如何通過本地存盤過濾回圈
