I am trying to use regular expression to find a specific word (with small or capital letters) in a text.
Examples are:
- none
- None
- NONE
However, the following code doesn't find the pattern in sample texts.
import re
txt_list = ["None" , "none", "[none]", "(NONE", "Hi"]
pattern = "/\bnone\b/i"
for txt in txt_list:
if re.search(pattern, txt):
print(f'Found {txt}')
What is the cause of the above issue? Is the "pattern" incorrect?
CodePudding user response:
Do not use slashes to delimit the regular expression. The syntax in Python is different. You can use (?i)
to ignore case. (Additionally, escape the backslashes or use raw strings.)
pattern = "(?i)\\bnone\\b"
You can also pass the re.IGNORECASE
flag to re.search
.
pattern = r"\bnone\b"
for txt in txt_list:
if re.search(pattern, txt, re.IGNORECASE):
print(f'Found {txt}')