Home > Mobile >  js regex not working. Exact match and or operation
js regex not working. Exact match and or operation

Time:02-02

The first 3 characters needs to be:

  • Exactly either ABC or ACD or BCD
  • Then followed be a hyphen -
  • Then followed by either a 5 or 8
  • Then any 4 numbers

Examples:

ABC-56789 (True)
AAA-56789 (False)

I have tried this:

/^[^ABC$|^ACD$|^BCD$][*-][5|8][0-9]{4}$/

CodePudding user response:

Use this regex:

const regex = /^(?:ABC|ACD|BCD)-[58][0-9]{4}$/;
[
  'ABC-56789',
  'AAA-56789'
].forEach(str => {
  console.log(str, '==>', regex.test(str));
})

Output:

ABC-56789 ==> true
AAA-56789 ==> false

Explanation of regex:

  • ^ -- anchor at beginning of string
  • (?:ABC|ACD|BCD) -- non-capture group with OR combinations
  • - -- literla dash
  • [58] -- a 5 or 8
  • [0-9]{4} -- four digits
  • $ -- anchor at end of string

Learn more about regex: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex

CodePudding user response:

Use parentheses, not square brackets, to group alternation patterns:

^(ABC|ACD|BCD)-[58][0-9]{4}$

CodePudding user response:

How about use this expression?

^(ABC|ACD|BCD)-[5|8]\d{4}$

[] means character set. So, [ABC] means any A or B or C, not ABC. And ^ means negated in []. So, regex you used may not work fine. If you want to group the tokens, you should use (). You can also use \d (digit) instead of [0-9].

CodePudding user response:

You have to change the regex to the following:

/^(ABC|ACD|BCD)-(5|8)[0-9]{4}$/

[] match single characters, but you want to match three characters in the beginning, so you have to use the () to create a capturing group.

  • Related