Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript conditional regular expression if-then-else

I'm trying to limit the entries to a specific format.

If the entry has 5500 or 5100 such as 01\01-5500-000-00 then I want to have this:

^[0-9]{2,}\\[0-9]{2}\-[0-9]{4}\-[0-9]{3}\-$

But if the entry has anything other than 5500 or 5100 I want to have this:

^[0-9]{2,}\\[0-9]{2}\-[0-9]{4}\-[0-9]{3}\-[0-9]{2}$

How can this be accomplished with the if then else idea?

like image 524
user974061 Avatar asked Sep 29 '15 20:09

user974061


People also ask

Can you use regex in if statement JavaScript?

The RegEx variable can just then be combined with the test( ) method to check the string. As the result is just a returned boolean (true or false), it can be easily combined with an if/else statement or ternary operator to continue with further actions depending on whether the string is present or not.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.


1 Answers

Conditional regex syntax is not supported by JavaScript regex engine, but it can be worked around with a non-capturing group containing 2 alternatives:

  1. One with the positive look-ahead and

  2. The second with the reversed, negative look-ahead.

This regex meets your criteria and is JavaScript compatible:

^(?:(?=.*\b5[15]00\b)[0-9]{2,}\\[0-9]{2}-[0-9]{4}-[0-9]{3}-|(?!.*\b5[15]00\b)[0-9]{2,}\\[0-9]{2}-[0-9]{4}-[0-9]{3}-[0-9]{2})$

See regex demo

Let me break it down:

  • ^ - Start of string
  • (?:
    • (?=.*\b5[15]00\b)[0-9]{2,}\\[0-9]{2}-[0-9]{4}-[0-9]{3}- - First alternative with the (?=.*\b5[15]00\b) look-ahead that requires a whole word 5500 or 5100 inside the string, and the first pattern you have
    • | - alternation operator
    • (?!.*\b5[15]00\b)[0-9]{2,}\\[0-9]{2}-[0-9]{4}-[0-9]{3}-[0-9]{2}) - Second alternative that is prepended with the (?!.*\b5[15]00\b) negative look-ahead that makes sure there is no 5100 or 5500 inside the string, and only then matches your second pattern.
  • $ - end of string.
like image 126
Wiktor Stribiżew Avatar answered Oct 01 '22 03:10

Wiktor Stribiżew