我一直在尝试使用正则表达式来识别两个字符之间的单词,但我无法成功。这是我的代码:
re.match(r"\s*\#?\w*(\<)+\s*(?P<method>\w+)\s*(\>)+\w*", "# This <foo> truc")
该句子带有(或没有)python注释(#),并且必须显示分组方法。
感谢您的时间和帮助
答案 0 :(得分:0)
您需要更改正则表达式以在This
和<
之前包含可选空格,然后才能使用groups
属性:
some_match = re.match(r"\s*\#?\s*\w*\s*(\<)+\s*(?P<method>\w+)\s*(\>)+\w*", "# This <foo> truc")
some_match.groups()
('<', 'foo', '>')
some_match.groups(1)
'foo'
答案 1 :(得分:0)
您缺少一些空格匹配。在#
字符之后,<
之前和>
之后。
所以一种选择是添加缺少的空格匹配:
>>> m = re.match(r"\s*\#?\s*\w*\s*(\<)+\s*(?P<method>\w+)\s*(\>)+\s*\w*", "# This <foo> truc")
>>> m.group('method')
'foo'
但是,如果只需要<
和>
之间的值,则使用re.search
,您可以简单地使用正则表达式:
>>> r = re.search(r"\<(?P<method>[^\>]*)\>", "# This <foo> truc")
>>> r.group('method')
'foo'