首页 > 解决方案 > 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()它可能无法返回我正在寻找的家得宝的确切位置。

标签: pythonregex

解决方案


如果要获取括号中文本的位置,则需要指定将第一个组作为参数匹配到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.


推荐阅读