Regex to match set of two digits seperated by "."

Viewed 41

I am trying to match a regex to only select,

two digits followed by optional "." followed by two digits followed by optional "." followed by two digits followed by optional "." followed by two digits.

For example, if the input data is :

12.45.7810
12345678
12.34.56.78
1.234.56.78
12.45.7816 

Expected match is:

12345678
12.34.56.78

I am banging my head to understand why following is wrong:

^\d{2}\.*\d{2}\.*\d{2}\.*\d{2}$

My understanding I from above regex is as follow:

^ is start of line
followed by two digits followed by zero or more . character,
followed by two digits followed by zero or more . character,
followed by two digits followed by zero or more . character,
followed by two digits
followed by end of line $.

However, this is matching lines like 12.45.7816

1 Answers

Since \.* matches an empty string between 78 and 16, the 12.45.7816 matches.

To only match dots if they are present between all digit pairs, or no dots at all otherwise, you can use

^\d{2}(?:(?:\.\d{2}){3}|\d{6})$

See its graph:

enter image description here

See the regex demo

Details

  • ^ - start of string
  • \d{2} - two digits
  • (?:(?:\.\d{2}){3}|\d{6}) - either of the two alternatives:
    • (?:\.\d{2}){3} - three occurrences of a dot followed with two digits
    • | - or
    • \d{6} - six digits
  • $ - end of string
Related