Home > OS >  regex expression to find strings with two letters
regex expression to find strings with two letters

Time:11-10

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

CodePudding user response:

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

CodePudding user response:

Something like this?

(^|.*[^a-zA-Z0-9])HM([^a-zA-Z0-9].*|$)

CodePudding user response:

maybe this will work (in python)

([^a-z] )HM([^a-z])
  • Related