[英]Extract all substrings between two markers
我有一个字符串:
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"]
我在这里阅读了答案:
并尝试了这个但没有成功,
>>> 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)
Output:
['The String that I want ', 'Another string that I want ']
注意:
&
在re
模式中有特殊含义,如果你想要文字 & 你需要转义它( \&
).
匹配除换行符以外的任何内容search
, findall
更适合选择*?
是非贪婪的,在这种情况下.*
也可以,因为.
不匹配换行符,但在其他情况下,您可能会比您希望的结束匹配更多阅读模块re
文档以讨论原始字符串的使用和具有特殊含义的隐式字符列表。
使用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
只会捕获(...)
捕获组中出现的内容,这是您要提取的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.