需要在python中使用正则表达式来分隔信号定义

时间:2017-12-06 15:43:29

标签: python regex

包含信号定义的字符串的格式为

  

signal_a =(3 = BOX1:soc1.sig_a1 | BOX1:soc1.sig_a0; 2 = BOX2:band_x1; 1 =的Xbox:的Abis | xbox1:bbs.seg_b; 0 =行程:跳过); signal_b =超级:马里奥| repp:版本; signal_c =半:six_sig; signal_d =(1 =最后:端|开始:捻; 0 =演示:试验)

我想分离信号定义并将它们放在一个列表中。如下所示,

signalDefList = [
    'signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)',
    'signal_b=super:mario|repp:ver',
    'signal_c=semi:six_sig',
    'signal_d=(1=last:end|start:twist;0=demo:test)'
]

有人可以帮我吗?

2 个答案:

答案 0 :(得分:2)

代码

See regex in use here

;(?=signal)

替换:\n

用法

See code in use here

import re

r = r";(?=signal)"
s = "signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip);signal_b=super:mario|repp:ver;signal_c=semi:six_sig;signal_d=(1=last:end|start:twist;0=demo:test)"
print re.split(r,s)

输出:

['signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)', 'signal_b=super:mario|repp:ver', 'signal_c=semi:six_sig', 'signal_d=(1=last:end|start:twist;0=demo:test)']

结果

输入

  

signal_a =(3 = BOX1:soc1.sig_a1 | BOX1:soc1.sig_a0; 2 = BOX2:band_x1; 1 =的Xbox:的Abis | xbox1:bbs.seg_b; 0 =行程:跳过); signal_b =超级:马里奥| repp:版本; signal_c =半:six_sig; signal_d =(1 =最后:端|开始:捻; 0 =演示:试验)

输出

signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)
signal_b=super:mario|repp:ver
signal_c=semi:six_sig
signal_d=(1=last:end|start:twist;0=demo:test)

说明

  • ;字面匹配分号;
  • (?=signal)确保以下内容的正向前瞻signal字面意思

答案 1 :(得分:0)

正如已经回答的那样,您应该使用;(?=signal)

要获得所需的输出,请将其放在re.split()方法中:

import re
signalDefList = re.split(';(?=signal)', data)
signalDefList
#['signal_a=3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)',
# 'signal_b=super:mario|repp:ver',
# 'signal_c=semi:six_sig',
# 'signal_d=(1=last:end|start:twist;0=demo:test)']