Tutorial: Finding and Replacing Text in File Using Regular Expressions
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
titleattributes, 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
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.
Then, in the Replace field, type the following regular expression:where
$1refers to the first capture group and
$2refers 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
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:
Next, fill in the Replace field with the following expression:
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:
PyCharm suggests the following replacement: