获取两个字符串中的子字符串

Get a substring within two strings

我有一个非常非常大的字符串,其中包含来自某个系统的日志
我只想要以 <status> 开头并以 </status>.
结尾的部分 听说RegEx表达式是个好方法,但是不知道怎么用
有什么想法吗?

s = "Hello I am a very long string <status>I've got a lovely bunch of coconuts</status> here they are standing in a row"
excerpt = s.partition("<status>")[2].rpartition("</status>")[0]
print excerpt

结果:

I've got a lovely bunch of coconuts

如果 <status></status> 只出现一次,那么您可以使用 string_name[string_name.index("<status>") + 8: string_name.index("</status>"].

s = "test<status>test2</status>"
print s[s.index("<status>") + 8: s.index("</status>"]

输出:

test2

如果你想尝试正则表达式,这里有一个方法:

import re

regex = re.compile(r"\<status\>(.*?)\</status\>", re.IGNORECASE)
s = """This is some long random text <status>This is the first status block</status> 
and some more text <status>and another block</status> 
and yet more <status>This is the last status block</status>"""
print(re.findall(regex, s))

产量

['This is the first status block', 'and another block', 'This is the last status block']

Demo

此方法的主要优势在于它提取了一行中的 all <status>...</status> 个块,而不仅仅是第一个块。请注意,对于三引号字符串,<status></status> 需要在同一行。