1

I have to replace text this way:

Some data la-la-la [image=test.png] next data...
Some data la-la-la 123 [image=test2.png]

And replace that with:

Some data la-la-la test.png next data...
Some data la-la-la 123 test2.png

I tried with re.sub method from python:

for foo in re.search('(\[image=(.*)\])', text):
   text = re.sub("(?<=\[image=)*(?=\])", foo, text)

But that won't work, why?

3
  • 2
    -1: Do it for me question disguised with random nonsense attempts without any effort of reading at least the minimal part of the API Commented Dec 14, 2010 at 14:25
  • @nosklo +1 flag for Unnecessary Rudeness. Commented Dec 14, 2010 at 14:33
  • @nosklo Yeah, it is. My bad. Not a random attemp :) Commented Dec 14, 2010 at 14:34

1 Answer 1

4

Seriously, did you read regex documentation or at least the howto?

  • .search() returns a match object. You can't iterate over it.
  • .sub() replaces all occurrences in the string at once. You can't replace one by one.

One idea:

import re

text = """Some data la-la-la [image=test.png] next data...
Some data la-la-la 123 [image=test2.png]"""

text = re.sub(r'\[image\=([^\]]+)\]', r'\1', text)

print text

the results:

Some data la-la-la test.png next data...
Some data la-la-la 123 test2.png
Sign up to request clarification or add additional context in comments.

4 Comments

@Ock: this is about how to use Python, not regex.
Probably, yeah. I just rework some project, not mine. I haven't time to learn Python deeply. Please, help me.
Seriously, did you read the SO faq? Did you really say RTFM?...On SO?!!...Really?!?!?!?!
@Ockonal Don't try to win over the haters; you're not the jack-ass whisperer.

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.