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 expression to find strings with two letters

I need to find all strings where strings have letters "H" and "M" but no other letters before or after but other symbols are ok.
Valid strings:

HM
(HM)
&HM%
This is HM
HM are two letters

Invalid strings:

Marshmellows
asdfHMASDF
sfafhmasdf

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 may use this regex in ignore case mode:

/^(?:.*?[^a-z\n])?HM(?:[^a-z\n].*)?$/igm

RegEx Details:

  • ^: Start
  • (?:.*?[^a-z\n])?: Match an optional match of anything followed by a non-letter
  • HM: Match HM (ignore case)
  • (?:[^a-z\n].*)?: Match an optional non-letter followed by anything till end
  • $: End

or else using look arounds:

/^.*?(?<![a-z])HM(?![a-z]).*/igm

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