python - Python 正则表达式 - 有界词
问题描述
我一直在尝试使用正则表达式来识别两个字符之间的单词,但我无法成功。这是我的代码:
re.match(r"\s*\#?\w*(\<)+\s*(?P<method>\w+)\s*(\>)+\w*", "# This <foo> truc")
该句子有(或没有)python 注释 (#) 并且必须显示 group 方法。
感谢您的时间和帮助
解决方案
您需要更改正则表达式以在This
and之前包含可选空格<
,然后您可以使用该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'
推荐阅读
- html - HTML表单提交时出现文件未找到错误
- python - 如何根据另一列的条件更改列值?熊猫/蟒蛇
- wai-aria - NVDA 屏幕阅读器忽略顶部导航中的 aria-current="date"
- css - 如何更改表格标题边框颜色和大小?
- heroku - Heroku 应用程序无法在 Safari 上访问
- python - 项目目录外文件的 PyCharm 代码完成
- java - 使用 Java 线程的读写器问题
- azure-devops - Azure Repos Git 上的批准和检查被忽略
- python - 如何正确格式化 Selenium Python 中的元素?
- excel - 如何在工作表中查找数据,对其进行修改,然后使用宏将修改后的数据写回该行?