Typing in Your Own Replacement Text
As shown in the “replacing text match by fields with text matched by other fields”, RegexMagic can generate a replacement text along with the regular expression. If you’re already familiar, you may find it quicker to enter the replacement text yourself. This example shows how RegexMagic can use a replacement text that you provide. You can find this example as “Action: replacement text” in the RegexMagic library.
For this example, we’ll continue with the regular expression created in the example about the “pattern used by another field” pattern. That regular expression matches three numbers delimited by commas.
Now we want to use this regex in a search-and-replace that swaps the first and third numbers. This is done by adding capturing groups to the regex and using backreferences to those groups in the replacement text.
- On the Library panel, load RegexMagic.rml if it isn’t loaded already.
- In the list of RegexMagic formulas in the library, select “Pattern: pattern used by another field”.
- Click the Use button to populate the Samples, Match, and Action panels with the settings from the RegexMagic formula we just loaded. The Match panel defines 5 fields. Fields , , and match the three numbers. Fields and match the commas that delimit them.
- On the Action panel, click the New button to add a capturing group. Set the group to capture field . We’ll use numbered backreferences in our replacement text, so don’t bother naming the group.
- Click the New button again to add a group to capture field .
- Click the New button one more time to capture field .
- Select “replace whole regex match” in the “action to take” drop-down list.
- Select “enter a replacement with backreferences” in the “how to replace” drop-down list.
- Now we can enter our replacement text:
- On the Regex panel, select “C# (.NET 2.0–4.8 & .NET Core 1.0–3.0)” as your application, turn on free-spacing, and turn off mode modifiers. Click the Generate button, and you’ll get the regular expression below. If you compare this regex with the one we got in the example about the “pattern used by another field” pattern, you’ll see that three pairs of parentheses have been added. Those are our three capturing groups.
Required options: Free-spacing; ^$ match at line breaks.
The replacement text generated by RegexMagic is identical to the one we provided, because we selected the same replacement text flavor (JGsoft) on the Action and Regex panels.
Unused options: Case sensitive; Dot doesn’t match line breaks; Numbered capture.
- If we select a different replacement text flavor, RegexMagic converts the replacement text from the flavor selected on the Action panel to the flavor selected on the Regex Panel. If we select Python on the Regex panel, for example, RegexMagic generates the same regular expression, but a different replacement text:
The reason is that Python uses \1 rather than $1 for inserting backreferences into the replacement text.