问题
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