21

I can never seem to find any documentation on the regex for matching a capture group as part of the pattern. For example:

(\w\d\w):$1

..should match a4b:a4b

$1 doesn't work, but I know it's something similar. Anyone know?

1 Answer 1

29

In a regex pattern, a backreference to the first capturing group is always \1, not $1.

Reason: $ means "end of string" (or end of line, depending on context) in a regex.

In a replace pattern (which isn't a regex), some dialects allow $1 (e. g. .NET, Java, Perl and JavaScript), some allow \1 (Python and Ruby), and some allow both (PHP and JGSoft).

Edit: Since you wrote that you couldn't find any documentation on this, check out these overviews on regular-expressions.info:

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.