简体   繁体   English

找到匹配字符串或正则表达式的结束偏移量

[英]Find the end offset of a matched string or regex

str.find() returns the beginning offset of a match in a string. str.find()返回字符串中匹配项的起始偏移量。 How can one get the end offset? 怎么能得到结束偏移?

I know that one way is to add it to the length of the match. 我知道一种方法是将它添加到比赛的长度。 But is there a way to get it directly? 但有没有办法直接得到它?

eg 例如

>>> a = 'Lorem ipsum dolor sit amet'
>>> a.find('ipsum')
6

What I want is: 我想要的是:

>>> a.find('ipsum')+len('ipsum')
11

This is trivial in case of str.find() . str.find()情况下,这是微不足道的。 But gets more important in case of regex , since the length of the matched expression is not known beforehand. 但是在regex情况下变得更加重要,因为事先不知道匹配表达式的长度。

The objects returned by the search and match functions in Python's re module have a span() method that returns the start and end positions of the matched regular expression: Python的re模块中的searchmatch函数返回的对象有一个span()方法,它返回匹配的正则表达式的开始和结束位置:

>>> import re
>>> a = 'Lorem ipsum dolor sit amet'
>>> re.search('ipsum', a).span()
(6, 11)
>>> re.search('sum.*sit', a).span()
(8, 21)

The start and end positions can also be returned individually with .start() and .end() . 也可以使用.start().end()单独返回开始和结束位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM