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

How to match fixed length string with quantifiers

I have strings like this:

  • 123456-0001
  • 123456-0012
  • 123456-0123

How to match with next conditions:

  • chars count after – should be 4
  • zeros count variable – from 1 to 3

I found ^\d{6}-0+([1-9]+)$ pattern but it matches for 123456-001 or 123456-00001.

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 :

You can use

^\d{6}-(?=\d{4}$)0+([1-9]\d*)$

See the regex demo.

Details:

  • ^ – start of string
  • \d{6} – six digits
  • - – a hyphen
  • (?=\d{4}$) – from this position and to the end of string, there must be four digits
  • 0+ – one or more zeros
  • ([1-9]\d*) – Group 1: a non-zero digit and then any zero or more digits
  • $ – end of string (use \z if you need the very end of string).

Note:

  • (?=\d{4}$) is the positive lookahead that enforces the four digit only rule
  • 0+ – makes a zero required (so one or more zeros is enforced)
  • ([1-9]\d*) captures any non-zero digit and then any digits including zeros (0100 will now get matched, too.)

Also, consider checking \d vs. [0-9] at \d less efficient than [0-9].

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