|
|
RegExp substrings replacements |
|
Regular expressions give you an ability to make complex search queries.
However when it comes to replace operation, you may feel limited in abilities, since you are required to replace
this complex search expression with simple text. This is where substrings come to help you.
Example
Instead of reading boring theory, let's work with typical comparison problem. Suppose we have original document
with multiple dates in this format: September 12, 2003; September 25, 2002 etc. (For simplicity we will work only with September in this example).
Your colleague has made some changes and, among others, changed date format to read as 12.09.2003; 25.09.2002.
So here is a problem for us - ignore date format change. Our first approach could be very simple - replace all dates to empty string, we can do this by using "September \d{1,2},\d{4}" regexp.
However in this case we will miss changes made to the date itself. What we need is to combine replace string from matched parts of search expression, i.e. from substrings.
Step 1: Mark substrings
To mark substring in search expression, we use parenthesis: "September (\d{1,2}),(\d{4})". Substrings are numbered 1,2,... as they appear in original expression.
In our case if string September 12, 2003 will be matched, substring #1 = "12", substring #2 = "2003".
Step 2: Use substrings
To insert found substrings in replacement string, use $1, $2,... variables. Summarizing all this information, here is search/replace expressions to ignore date format change:
Search: September (\d{1,2}),(\d{4})
Replace: $1.09.$2
Where can I use it?
You can use this approach in both cases, when RegExps are used for replacement in Compare It!:
|