通过正则表达式 提取文本中两个单引号间的变量,并删除特定逻辑的字符
文本长是这个:str="df.loc[(df['age']<23)&(df['salary']>=4000)&(df['height']<160)]"
需求 和 我想要达到的结果:
①提取str文本中 两个小于号判断的变量 :age、height
②删除str文本中两个小于号判断的逻辑,返回”df.loc[(df['salary']>=4000)]"
①提取str文本中 两个小于号判断的变量 :age、height
②删除str文本中两个小于号判断的逻辑,返回”df.loc[(df['salary']>=4000)]"
import re
str="df.loc[(df['age']<23)&(df['salary']>=4000)&(df['height']<160)]"
res1 = re.findall(r"\['([^>]*?)'\]<",str)
res2 = re.sub(r"&?\([^>]*\)&?","",str)
print(res1)
print(res2)
输出:
['age', 'height']
df.loc[(df['salary']>=4000)]
讲解: