[英]How can I simplify this regex?
這是一個相當復雜的正則表達式:
^\s*(?:\d{2}|\d{2}\s*\d{2}|\d{2}\s*\d{2}\s*\d{2}|\d{2}\s*\d{2}\s*\d{2}\s*\d{2}|\d{2}\s*\d{2}\s*\d{2}\s*\d{2}\s*\d{2})\s*$
它以圖形方式變為:
如何減少?
我嘗試過積極的前瞻但沒有成功(例如, (?=\\d{4})[\\s\\d]+
)。
正則表達式:
以下是正則表達式必須匹配的一組有效輸入: https : //regex101.com/r/hN0pT4/7
// OK // NOK
12 123
1234 12 345
123456 123 45 45
12345678 1 2 3 4 5
1234567890 12 34 56 78 90 11
12 34
12 3456
12 34 56 78
12 34 567890
編輯解決方案: https : //stackoverflow.com/a/36361240/363573
最短/最簡單的是:
^ *(\d\d *){1,5}$
筆記:
\\d\\d
(4個字符)比\\d{2}
更短/更簡單(5個字符,帶有量詞) \\s
更簡單(2個字符) \\s*
因為內部表達式使用任何尾隨空格 查看通過所有已發布測試用例的實時演示 。
如果你真的需要允許其他空格字符(例如制表符),那么使用:
^\s*(\d\d\s*){1,5}$
這是我能做的最好的
^(\d{2} ?){1,5}$
^\s*(\d{2} *){1,5}\s*$ <--- forgot the whitespaces 0 to n times (edit)
^
:字符串的開頭
(\\d{2} ?)
:匹配數字對與可選項
{1,5}
:該組可以重復一到五次(最多5對)
$
:字符串結束
讓我們分解一下:
^\\s*(?:x)\\s*$
很容易:輸入的開始,任何空格,組x,任何空格,結束 - 簡直就在這里。 \\d{2}|\\d{2}\\s*\\d{2}|\\d{2}\\s*\\d{2}\\s*\\d{2}|\\d{2}\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}|\\d{2}\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}
\\d{2}
\\d{2}\\s*\\d{2}
\\d{2}\\s*\\d{2}\\s*\\d{2}
\\d{2}\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}
\\d{2}\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}
看模式? 它們都以\\d{2}
開頭,每次還有一個\\s*\\d{2}
- 最多4次。 所以這可以簡化為\\d{2}(?:\\s*\\d{2}){0,4}
把它放在一起就得到^\\s*(?:\\d{2}(?:\\s*\\d{2}){0,4})\\s*$
你可以試試這個
^\s*((?:\d{2}\s*){1,5})$
根據評論解釋(正則表達式細分 )
^ #Starting of string
\s* #Consume any spaces from starting
( #Capturing group to capture the whole string if it matches the below requirements (It is not necessary to use it if you are only matching the string)
(?:\d{2}\s*){1,5} #Non capturing group to check the pattern
)
$ #End of string
這是另一種方式:
(\d\s*\d\s*){1,5}
正確匹配所有OP的例子:
比賽12
比賽1234
匹配123456
比賽12345678
符合1234567890
比賽12 34
比賽12 3456
比賽12 34 56 78
比賽12 34 567890
沒有比賽123
沒有比賽12 345
不匹配123 45 45
不匹配1 2 3 4 5
這是我選擇的最終解決方案:
^(?:\s*\d{2}){1,5}$
謝謝大家!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.