对不起,问题有点尴尬。
我想知道如何将从两个子字符串中提取的一些信息存储到一个数组中。
以下是一个例子:
"4"
答案 0 :(得分:2)
使用正则表达式提取MESSAGE
标记之间的子字符串,并将它们附加到列表中。
import re
messages = """
<MESSAGE>How's it going</MESSAGE>
<MESSAGE>Go to bed</MESSAGE>
"""
data = []
matches = re.finditer(r'<MESSAGE>(.*?)</MESSAGE>', messages)
for x in matches:
data.append(x.group(1))
print(data)
答案 1 :(得分:2)
import re
Messages= "<MESSAGE>How's it going</MESSAGE>" \
'<MESSAGE>Go to bed</MESSAGE>'
#Using regex to find all the messages
Message=list(re.findall(r'<MESSAGE>(.*?)</MESSAGE>',Messages))
print(Message)
以上应该返回
["How's it going", 'Go to bed']
正则表达式解释
<MESSAGE> #what the result should precede by
( #Group start which is returned by findall
.* #Match multiple characters with the given conditions
? #Match as minimal set as possible, otherwise it would be greedy and match you across many tags
) #Group end which is returned by findall
</MESSAGE> #What the group should be followed by