【发布时间】:2021-05-06 15:23:40
【问题描述】:
我有一个正则表达式来匹配长文本中的单词,如下所示:
word = "word"
text = "word subword word"
def char_regex_ascii(word):
return r"\b{}\b".format(re.escape(word))
r = re.compile(my_regex(word), flags= re.X | re.UNICODE)
for m in r.finditer(text):
print(m)
输出:
word
word
\b的原因是我不想找到子字符串,而是完整的单词:比如我对匹配文本word中的单词word不感兴趣@987654325 @,但我只想要完整的单词作为结果,因此后面或预期是空格、逗号、点或任何类型的标点符号。
它适用于大多数情况,但如果我在 w.o.r.d. 之类的单词末尾插入一个点,则它不匹配,因为正则表达式的最后一个 \b 在点之后。
word = "w.o.r.d."
text = "w.o.r.d. subword word"
def char_regex_ascii(word):
return r"\b{}\b".format(re.escape(word))
r = re.compile(my_regex(word), flags= re.X | re.UNICODE)
for m in r.finditer(text):
print(m)
输出:
(nothing)
我看到使用\B 可以让它工作,但我应该在句子的开头和结尾做几次检查,尝试\b 和\B 的所有组合以找到很多单词。
word = "w.o.r.d."
text = "w.o.r.d. subword word"
def char_regex_ascii(word):
return r"\b{}\B".format(re.escape(word))
r = re.compile(my_regex(word), flags= re.X | re.UNICODE)
for m in r.finditer(text):
print(m)
输出:
w.o.r.d.
是否存在通用方法?
【问题讨论】:
标签: python regex word-boundary