Python复杂的拆分功能

时间:2018-09-13 07:19:55

标签: python python-2.7

_list = ['match','regex','find']
_str = 'find the match and then find the regex later on'

根据_list,能够将_str拆分为:?

['find',' the ','match',' and then ','find',' the ','regex',' later on']

请注意,拆分字符串为其余子字符串保持空格

欢呼

1 个答案:

答案 0 :(得分:0)

您可以将re.findall与以下正则表达式配合使用:

import re
print([s for m in re.findall(r'(^.*?|)({0})(.*?)(?={0}|$)'.format('|'.join(_list)), _str) for s in m if s])

这将输出:

['find', ' the ', 'match', ' and then ', 'find', ' the ', 'regex', ' later on']