简体   繁体   中英

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
  2. Not end with 4 zeroes
  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?

(I know I can just flip it in the JS with a ! , I'm looking for a regex solution)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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