1

I am trying to use the sub function in python but cannot get it to work. So far I have

content = '**hello**'
content = re.sub('**(.*)**', '<i>(.*)</i>', content)

I am trying to make the

**hello**

be replaced with

<i>hello</i>

Any ideas?

1
  • what is your expected output for something like **foo**bar** Commented Oct 13, 2012 at 11:43

1 Answer 1

3

You'll need to escape the * character, and use the replacement function:

content = '**hello**'
content = re.sub('\*\*(.*)\*\*', lambda p : '<i>%s</i>' % p.group(1), content)

As an alternative, you can use named groups.

content = re.sub('\*\*(?P<name>.*)\*\*', '<i>\g<name></i>', '**hello**')

Or as a better alternative, numbered groups.

content = re.sub('\*\*(.*)\*\*', '<i>\\1</i>', '**hello**')
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but it replaces with <i>(.*)</i> instead of <i>hello</i>
this doesn't gives the required answer.
Thanks, that works perfectly, but say I had hello and I only wanted to match it if it was hello how would I achieve that?
Instead of a replacement function, you could just use r'<i>\1</i>'

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.