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

Check occurences using regex

I search for a regex expression that should be either:

  • BILL followed by 10 digits ( the total length should be 14 )
  • AAAASPA followed by 6 digits ( the total length should be 13 )

I tried this ^(BILL\d{10}){14}|(AAAASPA\d{6}){13}$

But It does not work.

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

>Solution :

The (BILL\d{10}){14} matches BILL + 10 digits after it 14 times. This {14} quantifier is redundant here, since the length limit is set by the preceding pattern itself.

Also, the anchors are only applied separately to the alternatives, the first will only match at the start of string, and the other will match at the end of string.

You need to use

^(BILL\d{10}|AAAASPA\d{6})$

Or

^(?:BILL\d{10}|AAAASPA\d{6})$

If your regex flavor does not support \d, use [0-9].

See the regex demo.

Details:

  • ^ – start of string
  • ( – start of a grouping construct ((?:...) is a non-capturing group, not supported by POSIX regex flavor)
    • BILL\d{10}BILL string and then ten digits
    • | – or
    • AAAASPA\d{6}AAAASPA string and then six digits
  • ) – end of the grouping
  • $ – end of string.

Note the grouping here that ensures proper anchoring.

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