簡體   English   中英

找到匹配字符串或正則表達式的結束偏移量

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

str.find()返回字符串中匹配項的起始偏移量。 怎么能得到結束偏移?

我知道一種方法是將它添加到比賽的長度。 但有沒有辦法直接得到它?

例如

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

我想要的是:

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

str.find()情況下,這是微不足道的。 但是在regex情況下變得更加重要,因為事先不知道匹配表達式的長度。

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)

也可以使用.start().end()單獨返回開始和結束位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM