Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中有没有办法通过正则表达式找到子字符串索引?_Python_Regex_Indexing_String Matching - Fatal编程技术网

在python中有没有办法通过正则表达式找到子字符串索引?

在python中有没有办法通过正则表达式找到子字符串索引?,python,regex,indexing,string-matching,Python,Regex,Indexing,String Matching,我想找到子字符串的索引位置,但是子字符串很长,很难表达(多行,甚至需要转义),所以我想使用正则表达式来匹配它们,并返回子字符串的索引, 类似str.find或str.rfind的函数, 有一些软件包帮助吗?正则表达式“re”软件包应该会有帮助 正则表达式“re”包应该会有所帮助 类似的方法可能会奏效: import re def index(longstr, pat): rx = re.compile(r'(?P<pre>.*?)({0})'.format(

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

正则表达式“re”软件包应该会有帮助

    • 正则表达式“re”包应该会有所帮助


        • 类似的方法可能会奏效:

          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'])
          

          类似的方法可能会奏效:

          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'])
          
          对成功匹配的结果对象(所谓的匹配对象)使用
          .start()
          方法:

          如果匹配成功,
          mo.start()

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

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