我有一个正则表达式来匹配长文本中的词,如下所示:
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
不感兴趣文本 subword
,但我只想要完整的单词作为结果,所以后面或前面有空格、逗号、点或任何类型的标点符号。
它适用于大多数情况,但如果我在单词的末尾插入一个点,如 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.
是否存在通用方法?
答案 0 :(得分:0)
您可以将正则表达式模式 \w+(?:\.?\w+)*
与 re.findall
一起使用:
text = "w.o.r.d. subword word"
matches = re.findall(r'\w+(?:\.?\w+)*', text)
print(matches) # ['w.o.r.d', 'subword', 'word']
此处使用的模式将“单词”定义为:
\w+ one or more word characters
(?:
\.?\w+ followed by optional dot and one or more
word characters
)* zero or more times
在此定义下,首字母缩略词样式术语(例如 w.o.r.d.
)将被捕获为匹配项。