Split a string with multiple delimiters

我的未来我决定 提交于 2020-03-06 10:58:29

问题


I have the string "open this and close that" and I want to obtain "open this and" and "close that". This is my best attempt:

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

I'm using Python 3.4.

Split string with multiple delimiters in Python replaces the triggers. I need them, the script has to know if I want to turn off or on a light, and not only which light is.


回答1:


Assuming open and close are your keywords you could do :

import regex as re
print(re.search(r'(open.+)(close.+)', "open this and close that").groups())
('open this and ', 'close that')

Note that you don't erase the space character just before close




回答2:


You can simply use the grouping if you know what letter are you using.

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


来源:https://stackoverflow.com/questions/59746454/split-a-string-with-multiple-delimiters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!