Regex for matching 3 or 4 or 5 letter words starting with "ho", but not included hou in hour

Viewed 446

I would like to match words starting with "ho" in a text. Matching words length should be maximum 5 and it should exclude hou in hour.

I currently struggle in adding length limits and excluding hou in hour.

My code is here:

demotext="what I have to do is to love you forever. however, we only have one hour left to be together. whatttttttttt. hot. hottest."

m = re.findall(r'\bwh\w+|\bho\w+',demotext)

print(m)

Can anyone tell me how to do it?

2 Answers

You can use

\b(?:wh|ho(?!ur\b))[a-zA-Z]{1,3}\b

If the hours should also be excluded, add s? after r,

\b(?:wh|ho(?!urs?\b))[a-zA-Z]{1,3}\b

See the regex demo.

Regex details

  • \b - a word boundary
  • (?:wh|ho(?!urs?\b)) - Group 1: either wh, or ho not followed with ur and an optional s and a word boundary
  • [a-zA-Z]{1,3} - one, two or three letters
  • \b - a word boundary.

Python demo

import re
text = r"what I have to do is to love you forever. however, we only have one hour left to be together. whatttttttttt. hot. hottest."
print(re.findall(r'\b(?:wh|ho(?!ur\b))[a-zA-Z]{1,3}\b', text))
# => ['what', 'hot']

Funny one. This should do the trick \b(?!hour\b|hou\b)(ho[a-zA-Z]{1,3})\b.

Related