【问题标题】:is there a way find substring index through a regular expression in python?有没有办法通过python中的正则表达式找到子字符串索引?
【发布时间】:2010-10-12 03:08:27
【问题描述】:

我想找到一个子字符串的索引位置,但是子字符串很长并且难以表达(多行,甚至你需要为它转义)所以我想使用正则表达式来匹配它们,并返回子字符串的索引, 像 str.find 或 str.rfind 这样的函数, 对此有一些软件包帮助吗?

【问题讨论】:

    标签: python regex indexing string-matching


    【解决方案1】:

    对成功匹配的结果对象(所谓的匹配对象)使用.start()方法:

     mo = re.search('foo', veryLongString)
     if mo:
          return mo.start()
    

    如果匹配成功,mo.start() 将为您提供搜索字符串中匹配子字符串的(第一个)索引。

    【讨论】:

      【解决方案2】:

      这样的事情可能会奏效:

      import re
      
      def index(longstr, pat):
          rx = re.compile(r'(?P<pre>.*?)({0})'.format(pat))
          match = rx.match(longstr)
          return match and len(match.groupdict()['pre'])
      

      然后:

      >>> index('bar', 'foo') is None
      True
      >>> index('barfoo', 'foo')
      3
      >>> index('\xbarfoo', 'foo')
      2
      

      【讨论】:

        【解决方案3】:
        猜你喜欢
        • 1970-01-01
        • 2012-05-09
        • 2017-07-04
        • 2021-03-29
        • 1970-01-01
        • 1970-01-01
        • 2016-05-16
        • 2017-07-26
        • 1970-01-01
        相关资源
        最近更新 更多