【问题标题】:Extract all substrings between two markers提取两个标记之间的所有子字符串
【发布时间】:2020-06-12 10:41:15
【问题描述】:

我有一个字符串:

mystr = "&marker1\nThe String that I want /\n&marker1\nAnother string that I want /\n"

我想要的是标记 start="&maker1" 和 end="/\n" 之间的子字符串列表。因此,预期的结果是:

whatIwant = ["The String that I want", "Another string that I want"]

我在这里阅读了答案:

  1. Find string between two substrings [duplicate]
  2. How to extract the substring between two markers?

并尝试过,但没有成功,

>>> import re
>>> mystr = "&marker1\nThe String that I want /\n&marker1\nAnother string that I want /\n"
>>> whatIwant = re.search("&marker1(.*)/\n", mystr)
>>> whatIwant.group(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

我能做些什么来解决这个问题?另外,我有一个很长的字符串

>>> len(myactualstring)
7792818

【问题讨论】:

    标签: python python-3.x python-2.7 python-re


    【解决方案1】:

    我能做些什么来解决这个问题? 我会这样做:

    import re
    mystr = "&marker1\nThe String that I want /\n&marker1\nAnother string that I want /\n"
    found = re.findall(r"\&marker1\n(.*?)/\n", mystr)
    print(found)
    

    输出:

    ['The String that I want ', 'Another string that I want ']
    

    注意:

    • &amp; 在re 模式中具有特殊含义,如果您想要文字并且需要转义它(\&amp;)
    • . 匹配除换行符以外的任何内容
    • findall 更适合选择如果您只想要匹配的子字符串列表,而不是 search
    • *? 是非贪婪的,在这种情况下 .* 也可以工作,因为 . 不匹配换行符,但在其他情况下,您可能会比您希望的结束匹配更多
    • 我使用所谓的原始字符串(r 前缀)使转义更容易

    阅读模块redocumentation,讨论原始字符串的使用和具有特殊含义的隐含字符列表。

    【讨论】:

    • 正则表达式模块可以处理的字符串长度是否有限制?
    【解决方案2】:

    考虑使用re.findall:

    mystr = "&marker1\nThe String that I want /\n&marker1\nAnother string that I want /\n"
    matches = re.findall(r'&marker1\n(.*?)\s*/\n', mystr)
    print(matches)
    

    打印出来:

    ['The String that I want', 'Another string that I want']
    

    下面是正则表达式模式的解释:

    &marker1      match a marker
    \n            newline
    (.*?)         match AND capture all content until reaching the first
    \s*           optional whitespace, followed by
    /\n           / and newline
    

    请注意,re.findall 只会捕获出现在 (...) 捕获组中的内容,也就是您要提取的内容。

    【讨论】:

      猜你喜欢
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      • 2015-05-05
      相关资源
      最近更新 更多