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 match specific strings

I want to capture all the strings from multi lines data. Supposed here the result and here’s my code which does not work.

Pattern: ^XYZ/[0-9|ALL|P] I’m lost with this part anyone can help?

Result
XYZ/1
XYZ/1,2-5
XYZ/5,7,8-9
XYZ/2-4,6-8,9
XYZ/ALL
XYZ/P1
XYZ/P2,3
XYZ/P4,5-7
XYZ/P1-4,5-7,8-9

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 pattern could be:

^XYZ\/(?:ALL|P?[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*)$

The pattern in parts matches:

  • ^ Start of string
  • XYZ\/ Match XYX/ (You don’t have to escape the / depending on the pattern delimiters)
  • (?: Outer on capture group for the alternatives
    • ALL Match literally
    • | Or
    • P? Match an optional P
    • [0-9]+(?:-[0-9]+)? Match 1+ digits with an optional - and 1+ digits
    • (?: Non capture group to match as a whole
      • ,[0-9]+(?:-[0-9]+)? Match ,and 1+ digits and optional - and 1+ digits
    • )* Close the non capture group and optionally repeat it
  • ) Close the outer non capture group
  • $ End of string

Regex demo

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