Home > Enterprise >  Trying to replace values after dollar sign and before closing bracket with regex expression
Trying to replace values after dollar sign and before closing bracket with regex expression

Time:03-05

My goal is to use regex to replace everything after the dollar sign and before the closing bracket.

  sns.histplot($[DATA]['$[COLUMN]']

So $[Data] just becomes dataframe, and $[COLUMN], column_x. Having a strange time with the syntax if anyone could help

CodePudding user response:

You could just make the whole statement an interpolated string (f string) wrapped in an eval function and pass in two variables, one for the DataFrame name and the other for the column name. Something like this:

eval(f”sns.histplot({df}[{col_name}]”

CodePudding user response:

This does what you want /\$\[[^\]] \]/gm - this will match every "$[foo]" you have in a given string

Explanation:

First part of the match is the literal characters, which we have to escape in regex $[ with \$\[

Then we match any character that isn't a closing bracket "]", and we'll match between 1 and unlimited times with [^\]]

When we see the closing bracket, we want that to be the end of the match. We find that with \]

Adding gm at the end will make the regex keep going until it's found all the matches, since you specify that there can be more than one in a string.

  • Related