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.
\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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With