我想要使用正则表达式拆分字符串。
输入:
S1:1- first split begins.s2:1- first split ends.s1:2-second split begins.S2:2-second split ends,S1:3-third split begins.S2:3-third split ends.
输出:应该是一个包含我们拆分的表达式的列表
[S1:1 - 第一次分裂开始,s2:1 - 第一次分裂结束,S1:2秒分裂开始,S2:2秒分裂结束,S1:3 - 3分裂开始.....] < / p>
我想分开模式[s/S][1/2]:[0-9][0-9]
这就是我所拥有的,但它给了我一个额外的行并删除了我分裂的正则表达式。
import re
text="""S1:1- first Split begins.continue the sentence
s2:1- first split ends
s1:2-second split begins
S2:2-second split ends
S1:3-third split begins
S2:3-third split ends """
output=re.split("[Ss][12]:[0-9]*", text)
答案 0 :(得分:2)
我不太确定我明白你想要分割这个输入的位置,但如果你想要分割的文本包含在输出中,那么你需要有一个捕获模式:
re.split("([Ss][1-2]:[0-9]-)\s*", text)
结果:
['',
'S1:1-',
'first Split begins.continue the sentence\n ',
's2:1-',
'first split ends\n ',
's1:2-',
'second split begins\n ',
'S2:2-',
'second split ends\n ',
'S1:3-',
'third split begins\n ',
'S2:3-',
'third split ends ']
答案 1 :(得分:2)
尝试在Regex中使用Positive Lookahead (?= CODE )
来完成此操作以保留正则表达式。你的正则表达式将是这样的:
\s(?=[sS][12]:[0-9])
完整代码:
import re
text="""S1:1- first Split begins.continue the sentence
s2:1- first split ends
s1:2-second split begins
S2:2-second split ends
S1:3-third split begins
S2:3-third split ends """
output=re.split("\s(?=[sS][12]:[0-9])", text)
结果:
['S1:1- first Split begins.continue the sentence\n ', 's2:1- first split ends\n ', 's1:2-second split begins\n ', 'S2:2-second split ends\n ', 'S1:3-third split begins\n ', 'S2:3-third split ends ']