简体   繁体   中英

How to use regex placeholder in PyCharm replace function

I have a Python file where are many lines like this one:

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['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.
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:

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.


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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