Python基于条件分割字符串

and*_*234 5 python regex string split

如果逗号前面是某个正则表达式,我想使用逗号分隔符分割字符串。考虑我的字符串采用以下格式的情况:“(一堆可能有逗号的东西)FOO_REGEX,(其他可能有逗号的东西)FOO_REGEX,...”我想用逗号分割字符串,但前提是它们前面是 FOO_REGEX:[“(一堆可能有逗号的东西)FOO_REGEX”,“(其他可能有逗号的东西)FOO_REGEX”,tc.]。

作为一个具体的例子,考虑拆分以下字符串:

"hi, hello! $$asdf, I am foo, bar $$jkl, cool" 
Run Code Online (Sandbox Code Playgroud)

进入这个包含三个字符串的列表:

["hi, hello! $$asdf", 
"I am foo, bar $$jkl", 
"cool"]
Run Code Online (Sandbox Code Playgroud)

在 python 中有什么简单的方法可以做到这一点吗?

Wik*_*żew 1

如果 FOO_REGEX 是固定宽度的,则可以使用正向后查找。在这里,您将在“$$asdf”之后分割行,

查看示例工作程序

import re    
str = 'hi, hello! $$asdf, I am foo, bar $$jkl, cool'
splts = re.split('(?<=\$\$asdf), *', str)
print splts
Run Code Online (Sandbox Code Playgroud)

输出:

['hi, hello! $$asdf', 'I am foo, bar $$jkl, cool'] 
Run Code Online (Sandbox Code Playgroud)