[英]How can I use re's special characters when splitting a string?
假設我有一個名為string
變量。
string = "Hello(There|World!!"
由於我想分割多個定界符,因此我使用re.split()
來完成這項工作。 不幸的是,該字符串包含re
模塊使用的特殊字符。 我不想使用re.escape()
因為那樣也可以避開感嘆號。 如何不使用re.escape()
分割re
的特殊字符?
使用字符類定義要分割的字符。
我認為您可能想保留這些感嘆號。 如果是這樣的話..
>>> s = "Hello(There|World!!"
>>> re.split(r'[(|]+', s)
['Hello', 'There', 'World!!']
如果您也想在感嘆號上分開。
>>> s = "Hello(There|World!!"
>>> re.split(r'[(|!]+', s)
['Hello', 'There', 'World', '']
如果要拆分其他字符,只需繼續將它們添加到班級中即可。
>>> s = "Hello(There|World!!Hi[There]"
>>> re.split(r'[(|!\[\]]+', s)
['Hello', 'There', 'World', 'Hi', 'There', '']
然后使用filter
刪除列表中的None元素。
re.split(r"\(|\||!",x)
Output:['Hello', 'There', 'World', '', '']
您可以使用多個定界符進行分割。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.