Python正则表达式返回括号内字符串的位置
使用正则表达式,我试图得到括号内字符串的位置 例如,我想得到“家得宝”的职位 但是,Python正则表达式返回括号内字符串的位置,python,regex,Python,Regex,使用正则表达式,我试图得到括号内字符串的位置 例如,我想得到“家得宝”的职位 但是, regex_.search(sent).span() 返回(0,55)而不是(45,55) 由于sent中可能有多个“home depot”,因此我无法使用re.search('home depot',sent).span(),它可能无法返回我要查找的home depot的确切位置。使用正向查找: sent = "Sales to two of the segment's customers, The Hom
regex_.search(sent).span()
返回(0,55)
而不是(45,55)
由于sent中可能有多个“home depot”,因此我无法使用
re.search('home depot',sent).span()
,它可能无法返回我要查找的home depot的确切位置。使用正向查找:
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(r"(?<=Sales to two of the segment's customers, The )Home Depot")
print(regex_.search(sent).span())
你的正则表达式是正确的。但你要求的是整场比赛的位置,而不是替补赛。要获取第一个子匹配的位置,请使用
span(1)
如果要获取括号中文本的位置,需要指定将第一个组作为参数匹配到
span()
:
请参阅上的python文档。为什么字符串硬编码到正则表达式中?那没什么大不了的sense@CertainPerformance哦事实上,我所想知道的只是当我知道“家得宝”这个词背后的含义时,找出它的位置。我首先想到的是Regex,因此我尝试了一下。有什么方法可以推荐给我吗?谢谢!这正是我需要的!谢谢
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(r"(?<=Sales to two of the segment's customers, The )Home Depot")
print(regex_.search(sent).span())
(45, 55)
>>> regex_ = re.compile("Sales to two of the segment's customers, The (Home Depot)")
>>> regex_.search(sent).span(1)
(45, 55)
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)