简体   繁体   English

使用多个分隔符拆分字符串

[英]Split a string with multiple delimiters

I have the string "open this and close that" and I want to obtain "open this and" and "close that" .我有字符串"open this and close that" ,我想获得"open this 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.我正在使用 Python 3.4。

Split string with multiple delimiters in Python replaces the triggers. Python 中带有多个分隔符的拆分字符串会替换触发器。 I need them, the script has to know if I want to turn off or on a light, and not only which light is.我需要它们,脚本必须知道我是想关灯还是开灯,而不仅仅是哪个灯。

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)

Assuming open and close are your keywords you could do :假设openclose是您可以执行的关键字:

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请注意,不要在关闭之前擦除空格字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM