python - Python正则表达式返回括号内字符串的位置
问题描述
使用正则表达式我试图在括号内获取字符串的位置。
例如我想获得“家得宝”的位置;
sent = "Sales to two of the segment's customers, The Home Depot and Lowe's Home Improvement Warehouse, accounted for greater than 10% of the Corporation's consolidated sales for 2004, 2003, and 2002."
regex_ = re.compile("Sales to two of the segment's customers, The (Home Depot)
然而,
regex_.search(sent).span()
(0, 55)
不返回(45, 55)
由于发送的可能有多个“家得宝”,我无法使用re.search('Home Depot', sent).span()
它可能无法返回我正在寻找的家得宝的确切位置。
解决方案
如果要获取括号中文本的位置,则需要指定将第一个组作为参数匹配到span()
:
sent = "Sales to two of the segment's customers, The Home Depot and Lowe's Home Improvement Warehouse, accounted for greater than 10% of the Corporation's consolidated sales for 2004, 2003, and 2002."
regex_ = re.compile("Sales to two of the segment's customers, The (Home Depot)
regex_.search(sent).span(1)
请参阅有关匹配对象的 python 文档和span
.
推荐阅读
- c++ - 致命错误:wchar.h:没有这样的文件或目录
- java - 如何在java中添加新行
- thymeleaf - 如何使用 thymleaf 中的另一个对象设置对象的值?
- sql - Postgresql:减少从选择中插入的内存需求
- django - 创建一个 Django 夹具文件,当加载到 DB 时,该文件保留一些字段不变
- microsoft-graph-api - 使用 Graph API 删除 Microsoft Teams 频道消息
- scala - 如何在 Slick 中更新表查询
- kdb - 更新 KDB 表中的嵌套表列表
- r - 使用 ggplot2 和 RMapShaper 平滑地图边界
- shell - 如何使用 awk 命令丢弃文件内容的最后一个字段