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.

1

2 Answers 2

3

\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')
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.