“NoneType”对象没有属性“groups”

2024-06-16 10:13:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代号:

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

但是结果的价值是没有,我不知道为什么。在

如果我缺少一些非常基本的东西,请告诉我。在


Tags: researchfoobarresultsentencewordgroups
1条回答
网友
1楼 · 发布于 2024-06-16 10:13:22
>>> 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()

相关问题 更多 >