我有一个日志,其中包含来自具有给定缓冲区长度的 TCP 端口的数据。每个事件都有一个可变长度,由 <+++> 和 <---> 分隔。
例子:
s = '<+++>A1 , Some Text, Other Text=12327463, Some Other Text<--->
<+++>A2, Some Text, IP=0.0.0.0, DateTime=12/07/2018 <---> <+++> A3, Some Text, Other Text=12327463, Some Other Text,
Text<---><+++>A3, New Text, IP=0.0.0.0, DateTime=12/07/2018, Text3Text3Text3, Text3Text3Text3, Text3Text3Text3,
Text3Text3Text3<--->Text4Text4Text4Text4Text4Text4Text4Text4Text4Text4Text4Text4Text4Text4Text4
Text4<---><+++>Text5Text5Text5Text5Text5Text5Text5Text5<---><+++>Text6Text6Text6Text6Text6Text6Text6Text6Text6<--->'
我需要拆分它,以便每个事件都是列表的元素——像这样:
['A1 , Some Text, Other Text=12327463, Some Other Text' , 'A2, Some Text, IP=0.0.0.0, DateTime=12/07/2018', 'A3, Some Text, Other Text=12327463, Some Other Text']
Text']
你会如何使用 Python 来做到这一点?
最佳答案
您也可以使用正则表达式来完成此任务,re.findall
特别是:
import re
s = '<+++>A1 , Some Text, Other Text=12327463<---> <+++>A2, IP=0.0.0.0 <--->'
re.findall(r'<\+\+\+>(.+?)<--->', s)
# ['A1 , Some Text, Other Text=12327463', 'A2, IP=0.0.0.0 ']
捕获的组(.+?)
代表任意字符(.
)的一个或多个(+
)非贪婪( ?
) 匹配,以免捕获从第一个开始到最后一个结束标记的整个部分。
关于python - 用不同的开始和结束分隔符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51307352/