Find & Replace is a life saver feature for any programmer. In this article we will discuss how to use Find and Replace in complex situations with Regular Expressions.

Find using Regular expressions

Many times we need to find some text in source code using Regular Expression and that’s not much difficult i.e.

Suppose I want to search text that starts with m_ and ends with end() . To do this we need to regular expression feature of IDE like Eclipse or Visual Studio i.e.

Above expression will search for text that starts with m_ and after there can be one or more characters and in the end there will be string end(). Also all the characters that comes under (.+) will be considered as a group.

With this regular expression we will be able to search text like,

Replace using Regular expressions

Now suppose we want to search and replace text like this,

to

and

to

We can not do this direct find and replace because in every matched text there is some mismatch in data that we need to maintain while converting this text to other format.

 

To do this we will use find and replace with regular expressions i.e. create groups while searching using regular expression and these groups will be passed to Replace operation as arguments. In replace expression these groups can be accessed using $i i.e. $1 or $2 etc..

Let’s see how to find and replace above example using regular expression,

Find expression :

Here Content in () i.e. .+ will be considered as a group and hence it will be passed to replace expression internally. Let’s use this in Replace Expression,

Replace expression :

Now this replace expression will convert ,

m_Data.end()  to m_pData->end() and m_Value.end()  to m_pValue->end()

Similarly during search we can create multiple groups and can use them in replace expression.