conditional logic in regular expression

Viewed 100

I'm trying to get the following conditional logic with regular expression.

if (text starts with +61) {
  if (text after +61 is 1800) {
    // then match 6 digits after 1800. So, the regex until here should be +611800 and then 6 digits
  } else {
    // match 9 digits after +61
  }
}

I read on how to write conditional regular expressions. But, I'm stuck here with the following regular expression

^\+61((?=1800)\d{6}|\d{9})$

The above regex fails for this, but it has to be successful

  • +611800123456 (This has to be success)

And the following text passes the regex test but it has to fail

  • +61180012345 (This has to be fail)

Here are my tests in regexr site.

https://regexr.com/5ia2e

1 Answers

The (?=1800)\d{6} pattern means the first four digits matched with \d{6} must be 1800, while you want to match any six digits after 1800 substring. That means, you need to "convert" the non-consuming (?=1800) into a consuming 1800 pattern.

Also, note that \d{9} second alternative will match any nine digits, while you only want to match them if they do not start with 1800. You need to prepend that second alternative with a (?!1800) negative lookahead pattern. Unfortunately, JavaScript RegExp does not support conditional constructs, in PCRE, .NET, etc. you could use ^\+61(?(?=1800)1800\d{6}|\d{9})$, but not in this case.

Here, you can use

^\+61(?:1800\d{6}|(?!1800)\d{9})$

See the regex demo.

Details

  • ^ - start of string
  • \+61 - +61 substring
  • (?:1800\d{6}|(?!1800)\d{9}) - a non-capturing group matching either
    • 1800\d{6} - 1800 substring and then any six digits
    • | - or
    • (?!1800)\d{9} - any nine digits not starting with 1800
  • $ - end of string.
Related