Home > Net >  Find a pattern with hole in it in a string python
Find a pattern with hole in it in a string python

Time:10-15

I'm trying to get and replace a specific pattern in which I don't know every character, from a larger string, I have a string like that :

string = "data_table['something'][x] * a   b"

and I want to replace the part "data_table['something'][x]" of string into whatever I want, let's say "my_thing", but I don't know what 'something' and x are, it could be anything, I just know that 'something' is a string, and x an integer.

I would like at the end to have string = "my_thing * a b".

I have a way to do it by reading the string in a loop, but I'm sure there is a more elegant way to do it

Thank you !

CodePudding user response:

This is possible using regular expression's in python. The following code will do what you want:

import re
string = "data_table['something'][x] * a   b"
re.sub("data_table\[.*\]\[.*\]", "mything", string)

Which will give:

mything * a   b

The only downside here is that you will need to escape the square brackets, by putting backslashes ("\") around them since otherwise they will be interpreted as a regular expression construct. But since you say that only the 'something' and x may change, you should be fine with the above.

  • Related