2017-05-08 49 views
3

我一直在試圖想出以下字符串正則表達式:Python的正則表達式匹配每個支架元素

[1,null,"7. Mai 2017"],[2,"test","8. Mai 2018"],[3,"test","9. Mai 2019"] 

我想每個支架得到儘可能匹配輸出與它作爲像一個單一的元素含量以下:

[1,null,"7. Mai 2017"] 
[2,"test","8. Mai 2018"] 
[3,"test","9. Mai 2019"] 

我最初的天真的做法是這樣的:

(\[[^d],.+\])+ 

豪ver,。+規則太籠統了,最終會匹配整條線。 任何提示?

+1

哪裏串來的?這是一個JSON字符串嗎?請注意,從字符串的開頭和結尾添加'['和']'會使這個特殊的字符串JSON可以通過'json.loads()'加載。.. – alecxe

+0

您可以使用'r'\ [[^]] * ]'' – anubhava

+1

我想你也可以使用'ast.literal_eval()' –

回答

1

我不確定你想要解析的數據格式和它來自哪裏,但它看起來像JSON。對於這個特定字符串,將方括號從一開始和字符串的結尾使得JSON加載

In [1]: data = '[1,null,"7. Mai 2017"],[2,"test","8. Mai 2018"],[3,"test","9. Mai 2019"]' 

In [2]: import json 

In [3]: json.loads("[" + data + "]") 
Out[3]: 
[[1, None, u'7. Mai 2017'], 
[2, u'test', u'8. Mai 2018'], 
[3, u'test', u'9. Mai 2019']] 

注意如何null成爲Python的None

1

以下代碼將使用\[[^]]*]輸出您請求的內容。

import re 
regex = r'\[[^]]*]' 
line = '[1,null,"7. Mai 2017"],[2,"test","8. Mai 2018"],[3,"test","9. Mai 2019"]' 
row = re.findall(regex, line) 
print(row) 

輸出:

[ '[1,NULL, 「7麥2017。」]', '[2, 「測試」, 「8麥2018。」]',「[ 3, 「測試」, 「9。麥2019」]']

考慮更改nullNone因爲它蟒表示相匹配。

1

你可能會考慮的精彩模塊pyparsing做到這一點:

import pyparsing 

for match in pyparsing.originalTextFor(pyparsing.nestedExpr('[',']')).searchString(exp): 
    print match[0] 
[1,null,"7. Mai 2017"] 
[2,"test","8. Mai 2018"] 
[3,"test","9. Mai 2019"] 

(除非它實際上是JSON - 如果是使用JSON模塊...)