[英]How to write regular expression that covers small and capital letters of a specific word?
I am trying to use regular expression to find a specific word (with small or capital letters) in a text.我正在尝试使用正则表达式在文本中查找特定单词(小写字母或大写字母)。
Examples are:例子是:
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? “模式”不正确吗?
Do not use slashes to delimit the regular expression.不要使用斜杠来分隔正则表达式。 The syntax in Python is different. Python 中的语法不同。 You can use (?i)
to ignore case.您可以使用(?i)
忽略大小写。 (Additionally, escape the backslashes or use raw strings.) (此外,转义反斜杠或使用原始字符串。)
pattern = "(?i)\\bnone\\b"
You can also pass the re.IGNORECASE
flag to re.search
.您还可以将re.IGNORECASE
标志传递给re.search
。
pattern = r"\bnone\b"
for txt in txt_list:
if re.search(pattern, txt, re.IGNORECASE):
print(f'Found {txt}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.