I have these inputs:
s1 = 'I am using c programming'.
s2 = = 'I am usingc programming'.
I want to check if s1 or s2 contains the exact word c
.
running this regex on both s1 and s2, it does not give any output:
x=s1 #x=s2
if re.search(r'\bc\ \ \b', x):
print(x)
expected result: detect c in s1
CodePudding user response:
You may use this regex for this using different flavors of word boundaries:
\bc\ \ \B
RegEx Details:
\b
: Word boundary between a non-word and word characterc\ \
: Matchc
\B
: Inverse of word boundary to match where\b
doesn't match
Python Code:
>>> import re
>>> s1 = 'I am using c programming'
>>> s2 = 'I am usingc programming'
>>> rx = re.compile(r'\bc\ \ \B')
>>> print (rx.findall(s1))
['c ']
>>> print (rx.findall(s2))
[]
>>>
CodePudding user response:
You could do the following
import re
x = 'I am using c programming'
pattern = re.compile(" c\ \ ")
results = re.findall(pattern, x)
if results:
print(x)
If c
is not in the string, results
will be empty.