MichaelH
MichaelH

Reputation: 1620

Python Regexp Sub Function

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?

Upvotes: 1

Views: 375

Answers (1)

Andrew Walker
Andrew Walker

Reputation: 42490

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**')

Upvotes: 3

Related Questions