tags:

views:

94

answers:

2

I'm trying to do a replace of all instances of strings like

PageLocalize("Texts", "R73")

with something like

Texts.R73.Localise()

I have a regex for matching these strings:

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

And a replacement string:

$1.$2.Localise()

but The Regex Coach says my replacement result is

$1.$2.Localise()

What do I need to do to my regex to get the numbered groupings to work?

+2  A: 

It works fine in a test application:

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 results in:

Texts.R73.Localise()

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

On a separate note, do you know about named groups? They're easier to maintain, especially if you add new groups to the regex. Can't get Stackoverflow to display a named group regex without spaces, so here it is with spaces in between:

( ? < group_name > yourregex )

And in the replacement text:

${group_name}
Andomar
+2  A: 

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

\1.\2.Localise()

The result you are getting is only possible if $1 is not recognized as a backreference to Group 1.

Edit:

I just checked and RegexCoach appears to use the Perl Regex syntax. If that is so, then $1 would be a valid backreference to Group 1. Then it would seem that the engine is unable to match the groups.

AmitK
You mean \$1 I right?
Andomar
No, I meant \1. ;-)
AmitK
Just wondering, if it's a valid backreference, how come it ends up in the result string? I'd expect it to be replaced with an empty string at least.
Andomar
+1 You're right about RegexCoach, it works if you use \1 instead of $1. Turns out Regexcoach is not a .NET application!
Andomar
Lol! Thanks for the vote ! :D
AmitK