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

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

我有一个字符串:

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/

相关文章:

python - 使用 Python 进行 Excel

python - python33如何传输文本文件

python - 检查项目是否在列表中的最快方法 - Python

python - 从另一个非子文件夹导入 python 文件

python - 以 5 分钟为间隔对 DataFrame 进行分组

python - Tensorflow raw_rnn 从嵌入矩阵中检索形状为 BATCH x DIM 的张量

python - statsmodels 与 pymc 中的对数似然

python - 参数 'src' 的预期 cv::UMat

python - 如何从 python 脚本内部运行 python 命令?

mysql - Flask-SQLAlchemy:仅查询某些列,将一对多关系作为列表返回