首页 > 解决方案 > Python 正则表达式 - 有界词

问题描述

我一直在尝试使用正则表达式来识别两个字符之间的单词,但我无法成功。这是我的代码:

re.match(r"\s*\#?\w*(\<)+\s*(?P<method>\w+)\s*(\>)+\w*", "# This <foo> truc")

该句子有(或没有)python 注释 (#) 并且必须显示 group 方法。

感谢您的时间和帮助

标签: pythonregex

解决方案


您需要更改正则表达式以在Thisand之前包含可选空格<,然后您可以使用该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'

推荐阅读