How do I replace regular expressions with numbered groups?

I am trying to replace all instances of strings like

PageLocalize("Texts", "R73")

      

with something like

Texts.R73.Localise()

      

I have a regex to match these lines:

PageLocalize\("([A-Za-z]+)", "([A-Za-z0-9]{0,6})"\)

      

And the replacement string:

$1.$2.Localise()

      

but the Regex Trainer says my replacement result is

$1.$2.Localise()

      

What do I need to do for my regex to get numbered groups?

+1


a source to share


2 answers


I haven't used RegexCoach, but some Regex engines require you to specify a backslash back reference, like this:

\1.\2.Localise()

      

The result you are getting is only possible if $ 1 is not recognized as a backlink for group 1.



Edit:

I just checked and RegexCoach seems to be using Perl's Regex syntax. If so, then it $1

would be a valid inverse relationship to group 1. Then it seems that the engine is unable to match groups.

+2


a source


It works fine in a test app:

var r = new Regex(
    "PageLocalize\\(\"([A-Za-z]+)\", \"([A-Za-z0-9]{0,6})\"\\)");
var s = r.Replace("PageLocalize(\"Texts\", \"R73\")", "$1.$2.Localise()");
Console.WriteLine(s);

      

This leads to:

Texts.R73.Localise()

      

AmitK found the correct way to do this in Regex Coach, which uses \ 1 instead of $ 1. It turns out that RegexCoach is not a .NET application, so it doesn't use .NET regular expressions!



In a separate note, do you know about named groups ? They are easier to maintain, especially if you are adding new groups to the regex. There is no way to get Stackoverflow to display a named wildcard regex without spaces, so there are spaces between:

(? <group_name> yourregex)

And in the replacement text:

${group_name}

      

+2


a source







All Articles