简体   繁体   English

如何在 PyCharm 中使用正则表达式占位符替换 function

[英]How to use regex placeholder in PyCharm replace function

I have a Python file where are many lines like this one:我有一个 Python 文件,其中有很多这样的行:

df['A'] = df.T + df.N / df.R

I want to replace each df.something occurances with df['something'] , so the above line becomes:我想用df['something']替换每个df.something出现,所以上面的行变成:

df['A'] = df['T'] + df['N'] / df['R']

I activate the replace functionality with Ctrl + R , then I tick the Reg̲ex option and I successfully highlight every occurrances by searching for df.[AZ] , as [AZ] stands for each T , N , R and so on, as it is a placeholder.我使用Ctrl + R激活替换功能,然后勾选Reg̲ex选项,并通过搜索df.[AZ]成功突出显示每个出现,因为[AZ]代表每个TNR等等,因为它是占位符。
I do not know how to use the same placeholder in the "Replace with" box and, therefore, what to write: if I reuse [AZ] (image below) as placeholder and write df.['[AZ]'] I get this:我不知道如何在“替换为”框中使用相同的占位符,因此不知道要写什么:如果我重用[AZ] (下图)作为占位符并写df.['[AZ]']我得到这个:

df['A'] = df['[A-Z]'] + df['[A-Z]'] / df['[A-Z]']

在此处输入图像描述

What should I write as a placeholder in the bottom box?我应该在底部框中写什么作为占位符?

You need to search for你需要搜索

df\.([A-Z]+)

And replace this with并将其替换为

df\["$1"\]

Then 然后
df['A'] = df["T"] + df["N"] / df["R"]

becomes变成

df['A'] = df["T"] + df["N"] / df["R"]

You need to enable the regex mechanism (last one on the right).您需要启用正则表达式机制(右侧最后一个)。 Remember that [ , ] and .请记住[ , ]. are meta characters within regex, $1 is the first captured group content.是正则表达式中的元字符, $1是第一个捕获的组内容。


For the other direction, you could use 对于另一个方向,您可以使用
df\[(['"])(.+?)\1\]

and replace this with并将其替换为

df.$2

This will only work with single quotes though.不过,这仅适用于单引号。 For double and single quotes use对于双引号和单引号,请使用

df\[(['"])(.+?)\1\]

and replace it with并将其替换为

df.$2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM