[英]Word boundary detection doesn't seem to work for me in Python re
我尝试使用:
>>> wbpat='\btest\b'
>>> re.findall(wbpat, 'a test tested in testing')
预期得到的结果是['test'],但不知何故我得到了一个空列表。 可能是什么问题呢...
\\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中将原始字符串用于正则表达式是一个好习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.