Home > Back-end >  Regex to identify a specific pattern
Regex to identify a specific pattern

Time:04-13

I am writing regex to find a specific pattern in my string. I have to identify if the string satisfy all the pattern that I am looking for. I have following criteria:

  1. The name should start with either "P" or "Q" or "R"
  2. Following the first character the string should match either "XYZ" or "ABCD"
  3. If the XYZ is present then the 8th character should either be "H" or "D", if "ABCD" is present the 9th character should be either "H" or "D".

String could be:

PXYZ****H***** -> Should be true
QABCD****H***** -> Should be true
AXYG****Z***** -> Should be false
RABCD****H=D***** -> Should be true

I have tried if the string starts with ([P|Q|R])\w , not sure how to combine others.

CodePudding user response:

Use

^[PQR](XYZ|ABCD)....[HD].*

See regex proof.

EXPLANATION

^ asserts position at start of a line
 Match a single character present in the list below [PQR]
   PQR matches a single character in the list PQR (case sensitive)
 1st Capturing Group (XYZ.|ABCD.)
   1st Alternative XYZ.
     XYZ matches the characters XYZ literally (case sensitive)
 2nd Alternative ABCD.
   ABCD matches the characters ABCD literally (case sensitive)

 . matches any character (except for line terminators)
 . matches any character (except for line terminators)
 . matches any character (except for line terminators)
 . matches any character (except for line terminators)
 Match a single character present in the list below [HD]
   HD matches a single character in the list HD (case sensitive)
 . matches any character (except for line terminators)
 * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)

CodePudding user response:

What is specific about this regex is that:

  • starts with PQR
  • continues with XYZ or ABCD
  • has an H or D five chars before the end

Here's my attempt:

'^[PQR](XYZ|ABCD).*[HD].{5}$'

Does it work for you?

  • Related