[英]Extracting strings from regular expression Python
我正在使用Python,並試圖了解如何使用正則表達式。 我有一個這樣的字符串列表:
example = ['(string1)-(hello)', '(string2)-(world)']
在這里,我有2個用圓括號括起來的字符串,並且用任何東西隔開,所以我只對()中的內容感興趣。 我想獲取一個字符串列表:
example = ['string1', 'hello', 'string2' , 'world']
任何建議如何做到這一點?
將re.findall
函數與list_comprehension一起使用。
>>> example = ['(string1)-(hello)', '(string2)-(world)']
>>> [x for i in example for x in re.findall(r'\(([^\)]*)\)', i)]
['string1', 'hello', 'string2', 'world']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.