如果我interprete您的要求是正確的,下面的正則表達式沒有匹配的無效輸入相匹配的有效輸入。
^\D*\d*\D*\d?(?!\d+)$
解釋如下
> # ^\D*\d*\D*\d?(?!\d+)$
> #
> # Options: case insensitive;^and $ match at line breaks
> #
> # Assert position at the beginning of a line (at beginning of the string or
> after a line break character) «^»
> # Match a single character that is not a digit 0..9 «\D*»
> # Between zero and unlimited times, as many times as possible, giving back
> as needed (greedy) «*»
> # Match a single digit 0..9 «\d*»
> # Between zero and unlimited times, as many times as possible, giving back
> as needed (greedy) «*»
> # Match a single character that is not a digit 0..9 «\D*»
> # Between zero and unlimited times, as many times as possible, giving back
> as needed (greedy) «*»
> # Match a single digit 0..9 «\d?»
> # Between zero and one times, as many times as possible, giving back as
> needed (greedy) «?»
> # Assert that it is impossible to match the regex below starting at this
> position (negative lookahead)
> «(?!\d+)»
> # Match a single digit 0..9 «\d+»
> # Between one and unlimited times, as many times as possible,
> giving back as needed (greedy) «+»
> # Assert position at the end of a line (at the end of the string or before a
> line break character) «$»
你的第二個例子是錯誤的,不是嗎? – 2010-10-18 13:16:16
@GáborLipták:他只想檢查連續的數字,以便正確評估。 – poke 2010-10-18 13:17:53
難道你不能通過搜索'/ \ d {2,} /'真正簡化這個並且否定結果嗎? – thetaiko 2010-10-18 13:18:34