簡體   English   中英

從括號中提取文本

[英]Extract text from parenthesis

如何從以下字符串中提取括號內的文本:

string =  '{a=[], b=[abc, def], c=[ghi], d=[], e=[jkl], f=[mno, pqr, stu, vwx]}'

預期輸出為:

['abc','def','ghi','jkl','mno','pqr','stu','vwx']

正則表達式應該有幫助。

import re
string =  '{a=[], b=[abc, def], c=[ghi], d=[], e=[jkl], f=[mno, pqr, stu, vwx]}'
res = []
for i in re.findall("\[(.*?)\]", string):
    res.extend(i.replace(",", "").split())
print res

輸出:

['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']

使用較新的regex模塊的替代方法可能是:

(?:\G(?!\A)|\[)([^][,]+)(?:,\s*)?

分解,這說:

(?:\G(?!\A)|\[)  # match either [ or at the end of the last match
([^][,]+)        # capture anything not [ or ] or ,
(?:,\s*)?        # followed by , and whitespaces, eventually

在 regex101.com 上查看演示


Python

 import regex as re string = '{a=[], b=[abc, def], c=[ghi], d=[], e=[jkl], f=[mno, pqr, stu, vwx]}' rx = re.compile(r'(?:\\G(?!\\A)|\\[)([^][,]+)(?:,\\s*)?') output = rx.findall(string) print(output) # ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']

暫無
暫無

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

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