【问题标题】:Find the end offset of a matched string or regex查找匹配字符串或正则表达式的结束偏移量
【发布时间】:2015-03-12 21:06:08
【问题描述】:

str.find() 返回字符串中匹配项的开始偏移量。 如何获得结束偏移量?

我知道一种方法是将它添加到匹配的长度中。但是有没有办法直接获取呢?

例如

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

我想要的是:

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

str.find() 的情况下这是微不足道的。但在regex 的情况下变得更加重要,因为事先不知道匹配表达式的长度。

【问题讨论】:

  • str.rfind('ipsum') 找到结束偏移量..
  • 什么是re.find()
  • @letsc str.rfind() 与 str.find() 相同,只是从字符串末尾开始检查并在开头结束。它仍然返回匹配的开始。

标签: python regex string


【解决方案1】:

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() 分别返回开始和结束位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 2015-06-15
    • 2015-04-02
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多