簡體   English   中英

我如何使用正則表達式拆分此字符串

[英]How can i split this string using regular expressions

我有一個類似的字符串:

"'a b | c'\,\,\,  'd | e f' ,,, 'g | h"

我想使用 re.split 來獲取以下列表:

["a b|c", "d|e f", "g|h"]

我嘗試了以下但沒有得到我想要的 output ,基本上我需要擺脫除了字母和 pipe 運算符之外的所有東西,然后拆分。 一個問題是有時會同時使用 ' 和 ":

re.compile(r'[\"\',][\W+]', re.UNICODE).split(txt.lower())

去掉|周圍的空格作為拆分后的單獨步驟。

split = re.compile(r'[\"\',][\W+]', re.UNICODE).split(txt.lower())
cleaned = [re.sub(r'\s*\|\s*', '|', x) for x in split]

我不認為你可以只使用split 您可能無法擺脫第一個引號,或者最終會得到一個空的第一個項目。:

這是一次嘗試,但未能刪除初始'

re.split(r"(?<=.)'[^']+'", txt)

output: ["'ab | c", 'd | e f', 'g | h'] ["'ab | c", 'd | e f', 'g | h']

findall的替代方案:

re.findall(r"'([^']+)'?", txt)

output: ['ab | c', 'd | e f', 'g | h'] ['ab | c', 'd | e f', 'g | h']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM