Tutorial: Finding and Replacing Text in File Using Regular Expressions
Example code
Consider the following XML code fragment:
<new product="ij" category="105" title="Multiline search and replace in the current file" />
<new product="ij" category="105" title="Improved search and replace in the current file" />
<new product="ij" category="105" title="Regexp shows replacement preview" />
...
Finding and replacing a string using regular expression
Suppose you want to replace an attribute within an element (title
) with an expanded tag <title></title>
, which contains some arbitrary string in double-quotes within.
This is how it's done.
With the XML file in question opened in the editor, press Ctrl+R. The Replace pane appears on top of the editor.
Since you want to replace all the
title
attributes, regardless of the actual strings contained therein, use regular expressions. Make sure that the checkbox Regex is selected. Thus everything you type in the Search and Replace fields will be perceived as the regular expressions.- In the Search field, start typing regular expression that describes all
title
attributes.Note that though the regular expression\stitle="(.*)?"\s*(/>*)
\stitle=".*?"\s*[/>]*
matches contents of thetitle
attribute, it is recommended to capture the groups for referencing them in the Replace field. Then, in the Replace field, type the following regular expression:
where$2<title>$1</title>
$1
refers to the first capture group and$2
refers to the second capture group.Click Replace, or Replace All.
As you see, the second capture group (/>
) is moved ahead to close the <new> element, while the first capture group <
, which matches any string in double quotes, is moved to the element <title>
.
Changing case of the characters
Suppose now that you want to change characters os the search strings. Again make sure that Regex checkbox is selected.
In the Search field, type the search expression:
\stitle="(.*)?"\s*(/>*)
Next, fill in the Replace field with the following expression:
\U$1
The found occurrences are replaced with the upper-case characters:

Next, let's make the strings all lower-case. To replace occurrences with the lower-case characters, type the following replacement string:
\L$1
Then the suggested replacement will be:

And finally, if you want change the case of the first letter only, type the following replacement string:
\l$1
CLion suggests the following replacement:
