views:

45

answers:

2

I have the string page-24 and want to replace 24 by any other number.

The script is written in PHP and uses preg_replace, however this problem should be independent from the programming language.

My match pattern is: (.*-)(\d*)

The replace pattern would be: $1[insert number here]$2

The backreferences work, but I cannot insert a number into the given place in the replace pattern because the expression would be interpreted in a wrong way. (First backreference to 199th match, if I inserted 99 as number.)

Am I missing an escape character here?

+3  A: 

In PHP, the replacement string either looks like this:

'${1}[insert number here]$2'

Or like this (if it is in a double-quoted string):

"\${1}[insert number here]$2"

Example:

$s = 'page-24';
$out = preg_replace('/(.*-)(\d*)/', '${1}99$2', $s);
echo "out is $out"; //prints 'page-9924'

(You probably just want ${1}99, which would give 'page-99' rather than 'page-9924'.)

See here for documentation in PHP. Perl uses the same notation. Javascript, as far as I can tell, doesn't support the ${1} notation, but it will interpret $199 as ${199} if there are at least 199 matching parenthesis, as ${19}9 if there are at least 19 matching parens, and ${1}99 if there is at least 1 matching paren, or the literal string $199 if there are no matches. I don't know about other languages' implementations.

Jenni
+1  A: 

Can you use match pattern

(.*)-(\d*)

and replace pattern

$1-[new number]

Why is there a reference to $2 in the replace pattern if you want to replace it?

Ethan Shepherd