regexregex-groupregex-alternation

How to Regex a string


Is it possible to check with regex:

  1. the complete string are numbers AND
  2. the first character is a 7 or 8 then the complete length of the string must be 11 OR
  3. the first character is a 1 then the complete length of the string must be 10
  4. OR the first character is a 0 then the complete length of the string must be 18 AND on character 8 must be a 8 or 7 OR on character 9 must be a 1

I hope you can see what I mean. Hope the examples will help you to know what I mean.

Here is my solution(not working completely-> I don't know how to check if in case it starts with a 0 and it is 18 characters long the character on position 8 must be 7or8 or on position 9 the character must be 1):

^(?:[78]\d{10}|[1-69]\d{9}|[0]/d{18})$

For example:

Thank you!


Solution

  • You can use

    ^(?:[78]\d{10}|1\d{9}|0\d{6}(?:[87]\d|\d1)\d{9})$
    

    See the regex demo

    Details