Home > Software design >  How to get the match for the following use cases with the regex pattern that i have?
How to get the match for the following use cases with the regex pattern that i have?

Time:03-08

Hi Have the Following Regex written.

(?<!x)(\d{9}|\d{3}-\d{6}|\d{3}-\d{3}-\d{3})

I want to modify the existing Regex so that the below use cases can get a match, right now only few are matching.

Note:

  1. 9 digit Order numbers should not get detected if 'X or x' precedes the number and that part is working fine.
  2. 9 digit numbers, Non-numeric characters or whitespaces (up to 3) in between numbers should also get matched.

Use cases:

This is a list of Use cases that needs to be Matched

https://regex101.com/r/iFiwx5/1

Example: These are the use cases that needs to be matched with the regex.

  1. 123 45 6789
  2. 123-45-6789
  3. 123-45-6789
  4. 123 – 45 – 6789
  5. 123.45.6789
  6. 123_45_6789
  7. 123 456 789
  8. 123-456-789
  9. 123 – 456 – 789
  10. 123.456.789
  11. 123_456_789
  12. 1234 56 789
  13. 1234-56-789
  14. 1234 – 56 – 789
  15. 1234.56.789
  16. 1234_56_789
  17. 12 345 6789
  18. 12-345-6789
  19. 12 – 345 – 6789
  20. 12.345.6789
  21. 12_345_6789

Any help on this would be really good.

CodePudding user response:

If I understand problem correct, you may use this regex:

(?<!x)(?=(?:[._ –-]*\d){9})\d{2,}[._ –-]*\d{2,}[._ –-]*\d{2,}

RegEx Demo

Explanation:

  • (?<!x) Make sure digits are not preceded with letter x
  • (?=(?:[._ –-]*\d){9}) ensures presence of at least 9 digits separated with 0 or more allowed delimiters
  • [._ –-]*: allows for presence of 0 or more of these delimiters every 2 or more digits
  • Related