【问题标题】:Word boundary detection doesn't seem to work for me in Python re在 Python re 中,单词边界检测似乎对我不起作用
【发布时间】:2018-11-20 06:41:27
【问题描述】:

我尝试使用:

>>> wbpat='\btest\b'
>>> re.findall(wbpat, 'a test tested in testing')

预期得到的结果是 ['test'] 但不知何故我得到了一个空列表。可能是什么问题...

【问题讨论】:

标签: python regex


【解决方案1】:

\b 是退格的转义码(长度为 1 个字符串)。使用r'\btest\b'。前导 r 向 Python 解释器表明它应该将字符串中的每个字符解释为文字单个字符(“原始”字符串)并忽略转义序列。

例子:

>>> len('\btest\b')    # <backspace>test<backspace>
6
>>> len(r'\btest\b')   # <backslash>btest<backslash>b
8
>>> import re
>>> re.findall(r'\btest\b','a test tested in testing')
['test']

在 Python 中使用原始字符串作为正则表达式是一个好习惯。

【讨论】:

    猜你喜欢
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多