Home > Enterprise >  Regex match specific strings
Regex match specific strings

Time:03-08

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

Changed to
XYZ/1
XYZ/1,2-5
XYZ/5,7,8-9
XYZ/2-4,6-8,9
XYZ/A12345 after the slash limited to 6 alphanumeric chars
XYZ/LH-1234567890 after the /LH- limited to 10 numeric chars 

CodePudding user response:

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

CodePudding user response:

You can use this regex pattern to match those lines

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

Use the global g and multiline m flags.

Btw, [P|ALL] doesn't match the word "ALL".
It only matches a single character that's a P or A or L or |.

  • Related