[英]Reg-ex to parse a list with bracketed nested sub lists?
我正在嘗試重構一些 Python 代碼來解析以下格式的字符串:
thing_1,thing_2,things_3[thing_31,thing_32,thing_34[thing_341]],thing_5
最終結果是結構化結果,例如:
{
"thing_1": True,
"thing_2": True,
"thing_3": {
"thing_31": True,
"thing_32": True,
"thing_34: {
"thing_341": True
}
},
"thing_5": True,
}
實際上,這是 API 請求的字段列表(僅返回給定字段),支持為嵌套對象定義必需字段。
我一直在嘗試各種方法來編寫 reg ex(如果可能的話)。 我的想法是首先在括號的內容上解析它,同時保留每個括號之前的第一個元素,最后我只剩下外部頂級列表。 但這證明用正則表達式描述比用英語“說”更難。
下面是一些值得注意的嘗試,但那里的分組都是錯誤的。
(([a-z0-9_]+)(\[[a-z0-9,_*]+\]*)+)
([a-z0-9_]+)(\[[a-z0-9,_*]+\]*)
(?<=[a-z0-9_])(\[[a-z0-9,_*]+\]*)
這甚至可以以優雅的方式完成嗎?
謝謝!
由於您已經有一個解析器並且只是想知道另一種方法,您可以考慮
import json, re
s = "thing_1,thing_2,things_3[thing_31,thing_32,thing_34[thing_341]],thing_5"
s = re.sub(r'\w+(?![\[\w])', r'"\g<0>": true', s)
js = json.loads('{' + re.sub(r'\w+(?=\[)', r'"\g<0>":', s).replace('[', '{').replace(']', '}') + '}')
print (json.dumps(js, indent=4, sort_keys=True))
Output:
{
"thing_1": true,
"thing_2": true,
"thing_5": true,
"things_3": {
"thing_31": true,
"thing_32": true,
"thing_34": {
"thing_341": true
}
}
}
筆記:
re.sub(r'\w+(?,[\[\w])': r'"\g<0>", true', s)
- 包裝所有不緊跟的 1+ 個單詞字符塊[
帶雙引號,並在它們之后附加: true
re.sub(r'\w+(?=\[)', r'"\g<0>":', s)
- 包裝所有 1+ 字字符塊,緊跟[
帶雙引號,並附加:
在他們之后.replace('[', '{').replace(']', '}')
將所有[
替換為{
和]
替換為}
{...}
json.loads(s)
解析后, json.dumps(js, indent=4, sort_keys=True)
漂亮地打印 json 並轉儲它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.