簡體   English   中英

從正則表達式Python中提取字符串

[英]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.

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