Regular expression find and replace with Visual Studio

Recently I had an interesting problem. I had functions in the form of:

func(param, param2)

I had to replace func with func2 which didnt take param 2, but only func 2 where param 2 was equal to a certain value, say ... x. Param was completely unpredictable , except that it was a string.

Regular expressions saved the day:

regex: {func1\("}{.+}{", x\)}

replacement string: newFunc("\1")

func1("aaasdds", x)
func1("Goodbye cruel world!!!! :(", x)

becomes...

newFunc("aaasdds")
newFunc("Goodbye cruel world!!!! :(")

By creating groups with the curly brackets {} you can replace only certain parts of a string, and match things around it.

The nice thing I've noticed about the . character is that it matches until your next match string. Meaning you can put just about anything in a string and still pull it out of a function call. Even the string below is matched:

func1("Goodbye cruel ""world!!!! :(""", x)

In python you can use re.sub. There is a slight difference here though. The groups must be contained in round brackets().

IF you are a developer and are ever confronted with a batch of string replacements, and you do not use regex... you sir, are an idiot and your the torture of the mundane work is your fault only....

Comments