Parentheses in regular expression (RegEx) can be used for grouping expression and can be named. To name it, after the opening parenthesis follows it with the following:
?<name>
Within the same expression you can backreference the group using the following:
\k<name>
On the replace field, based on the group position it will be numbered starting from 1 and increasing from the left of the expression and must be preceded with dollar sign (i.e. $). Use this number to access the captured match.
Note: if your group exceeds a single digit use ${<nn>} (e.g. ${10}) notation.
Example
<?xml version="1.0"?> <fruits> <a>apple</a> <b></b> <c>cashew</c> <d></d> </fruits>
From the XML above find all the empty elements and add an attribute empty that is set to true.
Find | Replace | Comment |
<(?<tag>\w*[^>])></\k<tag>> | <$1 empty="true"></$1> | The named group (i.e. blue text) is assigned to $1.
The \k<tag> (i.e. green text) is the backreference. |
Leave a Reply