2024-06-16 10:13:22 发布
网友
我的代号:
compileObj = re.compile('\b%s\b'%word) result = compileObj.search(sentence[j]) print result.groups() word = foo sentence = foo bar (foo) bar foo-bar foo_bar foo'bar bar-foo bar, foo
但是结果的价值是没有,我不知道为什么。在
如果我缺少一些非常基本的东西,请告诉我。在
>>> import re >>> sentence = "foo bar (foo) bar foo-bar foo_bar foo'bar bar-foo bar, foo" >>> word = 'foo' >>> compileObj = re.compile(r'\b%s\b' % re.escape(word)) >>> result = compileObj.search(sentence) >>> print result.group() foo >>> print compileObj.findall(sentence) ['foo', 'foo', 'foo', 'foo', 'foo', 'foo']
可能的误解及相应的解释:
r'\bfoo\b' to make python not interpret the special characters (in this example the backslash
re.escape
.search()
.findall()
.finditer()
可能的误解及相应的解释:
r'\bfoo\b' to make python not interpret the special characters (in this example the backslash
`),并将它们原封不动地传递给正则表达式库。在re.escape
该词,以防它包含更多正则表达式特殊字符。在.search()
只找到第一个匹配项。要查找所有匹配项,请使用.findall()
或.finditer()
相关问题 更多 >
编程相关推荐