tags:

views:

37

answers:

3

How can I place characters directly next to a group reference in regex? For example, if I am replacing the expression "0([0-9])" with "\1 aaa" it will show the number with a space and then "aaa" next to it. I want to place "aaa" directly next to the number without a space in between them.

EDIT: Sorry, I forgot the issue in my example. I am trying to place a number directly next to the group reference, which does not work. I am using the Python re module.

A: 

Use \\g<1> instead of \1. This way, there is no ambiguity.

>>> re.sub("0([0-9])", "\\g<1>99", "02")
'299'
JG
A: 

I don't know Python, but try \{1}, or maybe ${1}. These are the syntax on most regex libraries.

Daniel
+1  A: 

Use \g instead of \n:

 re.sub(r'0([0-9])',r'\g<1>4',"foo02")

For more information: http://docs.python.org/library/re.html#re.sub

marco
Thanks. I didn't think it would be in the Python docs.
linkmaster03