3

I have a pattern

pattern = "hello"

and a string

str = "good morning! hello helloworld"

I would like to search pattern in str such that the entire string is present as a word i.e it should not return substring hello in helloworld. If str does not contain hello, it should return False.

I am looking for a regex pattern.

Jonathan Davies
  • 882
  • 3
  • 12
  • 27
Kailash Akilesh
  • 173
  • 2
  • 2
  • 7

2 Answers2

4

\b matches start or end of a word.

So the pattern would be pattern = re.compile(r'\bhello\b')

Assuming you are only looking for one match, re.search() returns None or a class type object (using .group() returns the exact string matched).

For multiple matches you need re.findall(). Returns a list of matches (empty list for no matches).

Full code:

import re

str1 = "good morning! hello helloworld"
str2 = ".hello"

pattern = re.compile(r'\bhello\b')

try:
    match = re.search(pattern, str1).group()
    print(match)
except AttributeError:
    print('No match')
user
  • 5,370
  • 8
  • 47
  • 75
2

You can use word boundaries around the pattern you are searching for if you are looking to use a regular expression for this task.

>>> import re
>>> pattern  = re.compile(r'\bhello\b', re.I)
>>> mystring = 'good morning! hello helloworld'
>>> bool(pattern.search(mystring))
True
hwnd
  • 69,796
  • 4
  • 95
  • 132