gpt4 book ai didi

python - 提取两个标记之间的所有子字符串

转载 作者:行者123 更新时间:2023-12-02 16:37:41 25 4
gpt4 key购买 nike

我有一个字符串:

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

最佳答案

我该怎么做才能解决这个问题?我会这样做:

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

注意:

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

读取模块re documentation用于讨论原始字符串用法和具有特殊含义的隐式字符列表。

关于python - 提取两个标记之间的所有子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62342552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com