首页 > 解决方案 > 拆分具有多个分隔符的字符串

问题描述

我有字符串"open this and close that",我想获得"open this and"and "close that"。这是我最好的尝试:

>>>print( re.split(r'[ ](?=(open|close)+)', "open this and close that") )
['open this and', 'close', 'close that']

我正在使用 Python 3.4。

Python 中具有多个分隔符的拆分字符串替换了触发器。我需要它们,脚本必须知道我是要关灯还是开灯,而不仅仅是哪个灯。

标签: pythonregexsplit

解决方案


如果您知道您使用的是什么字母,您可以简单地使用分组。

import re
line = re.sub(r"(open this and) (close that)", r"\1\t\2", "open this and close that")
print (line)

推荐阅读