0

How would I change....

"Take dog1 and dog5 to the dog kennel"

to

"Take animal_1 and animal_5 to the dog kennel"

? So I only want to substitute "animal_" for "dog" if "dog" has a number after it. Any help is welcome.

7
  • 1
    Did you try doing some research? The simplest way would be to match the digit and put it back in the replacement. Another way would be to use a lookahead. Commented Aug 26, 2014 at 16:22
  • I've read the python doc on regex, the tutorialspoint doc as well as these message boards. I've been playing around with my interpreter with no luck. I could do it with ordinary python but I figured there would be a short way with regex. Commented Aug 26, 2014 at 16:39
  • I gave you two hints with that comment. Did you make use of them? The lookahead itself takes a while to be understood usually. Commented Aug 26, 2014 at 16:41
  • I got my answer from a quick read of the python regex functions. But mine below is also the most basic. Commented Aug 26, 2014 at 16:45
  • @Jerry I said thats how I found my solution (answered below). I think you mean the guy who asked the question (user3319934) Commented Aug 26, 2014 at 17:24

3 Answers 3

1

You could try the below re.sub function,

>>> import re
>>> s = "Take dog1 and dog5 to the dog kennel"
>>> m = re.sub(r'dog(\d)', r'animal_\1', s)
>>> m
'Take animal_1 and animal_5 to the dog kennel'

Through lookahead,

>>> m = re.sub(r'dog(?=\d)', r'animal_', s)
>>> m
'Take animal_1 and animal_5 to the dog kennel'
Sign up to request clarification or add additional context in comments.

2 Comments

Ah! This is what I was looking for. It works. I couldn't find out how to reference the parameter. "\1" did the trick.
Thanks again. I'm a noob here.
1

you can probably do the following:

import re

old_sting = 'Take dog1 and dog5 to the dog kennel'

dog_finder = re.compile(r'dog(\d+)')
new_string = re.sub(dog_finder, lambda dog: 'animal_' + dog.group(1), old_sting)

Comments

1

Something like this:

>>> import re
>>> def dog_replace(matchobj):
...     number = matchobj.group(0)[-1:];
...     return "animal_"+ number
>>> re.sub('dog[0-9]', dog_replace, "Take dog1 and dog5 to the dog kennel")
"Take animal_1 and animal_5 to the dog kennel"

This works as I have tested it on my local machine. It is essentially the same as the lambda...i'm just an old bear and I think this is more readable.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.