正则表达式匹配不以模式结尾的字符串

Jel*_*ena 10 regex regex-negation

我试图找到一个匹配字符串的正则表达式,只有当字符串不以至少三个'0'或更多结束时才会结束.直觉上,我试过:

.*[^0]{3,}$
Run Code Online (Sandbox Code Playgroud)

但是当字符串末尾有一个或两个零时,这不匹配.

Tim*_*ker 13

如果你不必使用lookbehind断言(即在JavaScript中):

^(?:.{0,2}|.*(?!000).{3})$
Run Code Online (Sandbox Code Playgroud)

否则,请使用hsz的答案.

说明:

^          # Start of string
(?:        # Either match...
 .{0,2}    #  a string of up to two characters
|          # or
 .*        #  any string
 (?!000)   #   (unless followed by three zeroes)
 .{3}      #  followed by three characters
)          # End of alternation
$          # End of string
Run Code Online (Sandbox Code Playgroud)


hsz*_*hsz 9

您可以尝试使用负面的后视,即:

(?<!000)$
Run Code Online (Sandbox Code Playgroud)

测试:

Test  Target String   Matches
1     654153640       Yes
2     5646549800      Yes   
3     848461158000    No
4     84681840000     No
5     35450008748     Yes   
Run Code Online (Sandbox Code Playgroud)

请记住,每种语言都不支持负面观察.