Python 使用正则表达式从给定字符串中查找多个字符串
这是我的一根绳子。如何在python中使用正则表达式分隔“函数”、“程序”、“位置”等字符串 我希望以列表的形式输出,即Python 使用正则表达式从给定字符串中查找多个字符串,python,regex,Python,Regex,这是我的一根绳子。如何在python中使用正则表达式分隔“函数”、“程序”、“位置”等字符串 我希望以列表的形式输出,即 s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]" 试试这个: import re s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]" groups = re.findall("\
s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]"
试试这个:
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']
试试这个:
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']
您可以为此使用
re
模块,但是-至少对于您提供的示例数据-不必使用它来获得所需的输出,因为只要使用str
方法就足够了。即:
>>> re.findall(r'"([^"]*)"', s)
['function', 'program', 'location']
输出:
s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]"
lst = [i for i in s.split('"') if i.isalpha()]
print(lst)
此代码仅在
“
然后选择仅由字母字符组成且长度不小于1
的str
s,您可以使用re
模块,但是-至少对于您提供的示例数据-不必使用它来获得所需的输出,因为只要str
方法就足够了。”。即:
>>> re.findall(r'"([^"]*)"', s)
['function', 'program', 'location']
输出:
s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]"
lst = [i for i in s.split('"') if i.isalpha()]
print(lst)
此代码只需在
“
处拆分
,然后选择仅由字母字符组成且长度不小于1
的str
s,使用regex函数| program | location
有什么问题吗?regex是解析表达式的错误工具。您想要解析器吗(尽管基于regex的lexer在整个体系结构中可能是一个有用的组件)。使用regex函数|程序|位置
有什么问题吗?regex是解析表达式的错误工具。您需要一个解析器(尽管基于regex的lexer在整个体系结构中可能是一个有用的组件)。