Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex - Substring match [duplicate]

Tags:

python

regex

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.

like image 343
Kailash Akilesh Avatar asked Jun 03 '26 07:06

Kailash Akilesh


2 Answers

\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')
like image 87
user Avatar answered Jun 05 '26 00:06

user


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
like image 33
hwnd Avatar answered Jun 05 '26 00:06

hwnd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!