簡體   English   中英

Python正則表達式,拆分參數,忽略引號中的逗號

[英]Python regex, split arguments, ignore commas in quotes

假設我有一行包含以,

'0xe1b04048, FUTEX_WAIT, 0, NULL , "Hey, World, how, are, you"'

我想要python中的正則表達式,可將此序列拆分為包含項的列表(為清楚起見,逐行拆分一項)

[
'0xe1b04048', 
'FUTEX_WAIT', 
'0', 
'NULL',
'"Hey, World, how, are, you"'
]

我試圖使正則表達式具有負面的前瞻性,至少可以處理一個逗號的評論,而我的計划是擴展它,但我什至沒有做到。 調用re.split(r",\\s(?!\\".*,\\s.*\\")",args)

'0xe1b04048, FUTEX_WAIT, 0, NULL , "Hey, World"'

結果是

[
'0xe1b04048', 
'FUTEX_WAIT', 
'0', 
'NULL , "Hey', 
'World"'
]

您可以將csv模塊與skipinitialspace=True

例如:

import csv

with open(filename, "r") as infile:
    reader = csv.reader(infile, delimiter=",", skipinitialspace=True)
    for line in reader:
        print([i.strip("'") for i in line])

輸出:

['0xe1b04048', 'FUTEX_WAIT', '0', 'NULL ', 'Hey, World, how, are, you']

您可能應該為此使用csv 但是,如果你喜歡一個純Python的解決方案(無正則表達式要么,但是......),你可以試試這個:通過分割"第一,然后所有的偶數部分分裂,無論列表是否與字符串元素或不能啟動。 ,則字符串的內容將始終位於奇數位置。

>>> s = '"start", 0xe1b04048, FUTEX_WAIT, 0, NULL , "Hey, World, how, are, you", not, a, string, "another, string"'
>>> s.split('"')
['',
 'start',
 ', 0xe1b04048, FUTEX_WAIT, 0, NULL , ',
 'Hey, World, how, are, you',
 ', not, a, string, ',
 'another, string',
 '']

>>> [x.strip() for i, w in enumerate(s.split('"')) 
...            for x in (['"%s"'%w] if i%2 else w.split(", ")) if x]
['"start"',
 '0xe1b04048',
 'FUTEX_WAIT',
 '0',
 'NULL',
 '"Hey, World, how, are, you"',
 'not',
 'a',
 'string',
 '"another, string"']

當然,這是假定沒有嵌套或轉義的引號。

(將其發布為第二個答案,因為方法與第一個完全不同)。

如果你真的想用這個正則表達式,你可以試試這個: ".+?"|[^", ]+這只是看起來項目,是指包含在所有零件"或既不含"也沒有,或空間。

>>> s = '"start", 0xe1b04048, FUTEX_WAIT, 0, NULL , "Hey, World, how, are,  you", not, a, string, "another, string"'
>>> p = r'".+?"|[^", ]+'
>>> re.findall(p, s)
['"start"',
 '0xe1b04048',
 'FUTEX_WAIT',
 '0',
 'NULL',
 '"Hey, World, how, are, you"',
 'not',
 'a',
 'string',
 '"another, string"']

同樣,如果存在嵌套或轉義的引號,則此方法可能會崩潰,並且考慮使用csv所有方法可能都是更好的主意。

暫無
暫無

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

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