[英]Split a string with multiple delimiters
我有字符串"open this and close that"
,我想獲得"open this and"
和"close that"
。 這是我最好的嘗試:
>>>print( re.split(r'[ ](?=(open|close)+)', "open this and close that") )
['open this and', 'close', 'close that']
我正在使用 Python 3.4。
Python 中帶有多個分隔符的拆分字符串會替換觸發器。 我需要它們,腳本必須知道我是想關燈還是開燈,而不僅僅是哪個燈。
如果您知道使用的是什么字母,則可以簡單地使用分組。
import re
line = re.sub(r"(open this and) (close that)", r"\1\t\2", "open this and close that")
print (line)
假設open
和close
是您可以執行的關鍵字:
import regex as re
print(re.search(r'(open.+)(close.+)', "open this and close that").groups())
('open this and ', 'close that')
請注意,不要在關閉之前擦除空格字符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.