简体   繁体   English

正则表达式-如何转换成NOT

[英]Regular Expression - How to invert into NOT

I am trying to write a regular expression which I can chain a few not rules together. 我正在尝试编写一个正则表达式,可以将一些非规则链接在一起。 I need to validate a number string to check that it does NOT match a few rules. 我需要验证一个数字字符串以检查它是否与某些规则不匹配。

I need it to: 我需要它:

  1. Not start with 3 zeroes 不是以3个零开头
  2. Not end with 4 zeroes 不以4个零结尾
  3. Not be all the same digit 不能全部相同

Here is what I'm trying so far: 到目前为止,我正在尝试以下操作:

var re = new RegExp(/^(.)\1{8}$|^000|0000$/);

re.test("111111111"); // true; all same digit
re.test("000112222"); // true; starts with zeroes
re.test("111110000"); // true; ends in zeroes
re.test("123456789"); // false
re.test("111223344"); // false

This works for the first three cases by yielding TRUE, how can I invert the test to have it be false unless it meets the 3 rules? 对于前三种情况,这通过产生TRUE起作用,除非满足3条规则,如何才能将测试转换为假?

(I know I can just flip it in the JS with a ! , I'm looking for a regex solution) (我知道我可以用!在JS中翻转它,我在寻找正则表达式解决方案)

Putting all rules together, you can use this regex: 将所有规则放在一起,可以使用此正则表达式:

/^(?!0{3})(?!.*0{4}$)(\d)(?!\1*$)\d*$/gm

RegEx Demo 正则演示

RegEx Breakup: 正则表达式分解:

^           # start
(?!0{3})    # negative lookahead to assert failure when we have 3 0s at start
(?!.*0{4}$) # negative lookahead to assert failure when we have 4 0s at end
(\d)        # match a digit and capture in group #1
(?!\1*$)    # negative lookahead to assert we don't have same digit until end 
\d*         # match zero or more digits
$           # end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM