【问题标题】:Word boundaries to match strings containing dots (.) at begin/end [duplicate]在开始/结束处匹配包含点 (.) 的字符串的单词边界 [重复]
【发布时间】: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


    【解决方案1】:

    您可以使用正则表达式模式\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. 等首字母缩略词将被捕获为匹配项。

    【讨论】:

      猜你喜欢
      • 2013-01-27
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 2012-07-24
      • 1970-01-01
      相关资源
      最近更新 更多