Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex delimiter allow list but must all be the same

Is there a regex pattern that will have a list of allowed delimiters but enforce they all must be the same?

For an example, I will use a MAC Address:

xx:xx:xx:xx:xx:xx (allowed)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

xx-xx-xx-xx-xx-xx (allowed)

xx:xx-xx:xx-xx:xx (not allowed)

I am currently using this:

[RegularExpression("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}){1}$")]

>Solution :

You can use a capture group and a backreference:

^[0-9A-Fa-f]{2}(?=([:-]))(?:\1[0-9A-Fa-f]{2}){5}$
  • ^ Start of string
  • [0-9A-Fa-f]{2} Repeat the character class 2 times
  • (?=([:-])) Positive lookahead, assert and capture either : or -
  • (?:\1[0-9A-Fa-f]{2}){5} Repeat 5 times a backreference \1 to what is initially captured in group 1 followed by 2 times the character class
  • $ End of string

Regex demo

Or with an inline modifier for case insensitive if supported:

(?i)^[0-9a-f]{2}(?=([:-]))(?:\1[0-9a-f]{2}){5}$
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading