簡體   English   中英

使用正則表達式從給定的字符串中查找多個字符串

[英]Find multiple string from a given string using regex

s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]"

這是我的一個字符串。 如何在python中使用正則表達式分隔字符串,例如“函數”,“程序”,“位置”?

我希望輸出的列表,即

lst = ['function', 'program', 'location']

嘗試這個:

>>> re.findall(r'"([^"]*)"', s)
['function', 'program', 'location']

您可以為此使用re模塊,但是- 至少對於您提供的示例數據 -不必使用它來獲得所需的輸出,因為str方法就足夠了。 那是:

s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]"
lst = [i for i in s.split('"') if i.isalpha()]
print(lst)

輸出:

['function', 'program', 'location']

該代碼僅split s split" ,然后選擇僅由字母字符組成且長度不少於1 str

import re
s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]"
groups = re.findall("\"([a-z]+?)\"",s) # get groups of all letters which are between two `"`
print(groups) # -> ['function', 'program', 'location']

暫無
暫無

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

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