Tutorial: Finding and Replacing Text in File Using Regular Expressions
On this page:
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
<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
titleattributes, regardless of the actual strings contained therein, use regular expressions. Make sure that the check box 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
titleattributes. Note that though the regular expression
\stitle=".*?"\s*[/>]*matches contents of the
titleattribute, it is recommended to capture the groups for referencing them in the Replace field:
Note that for the regular expressions replacement preview is shown at the tooltip:
- Then, in the Replace field, type the following regular expression:
- 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
Changing case of the characters
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:
Then the suggested replacement will be:
And finally, if you want change the case of the first letter only, type the following replacement string:
PhpStorm suggests the following replacement: