0

I have a regex like this

value = ">>897897"
rep = "<div> \\1 </div>"
pat = "&gt;&gt;(\\d+)"
res = re.sub(pat, rep, value)

But now I want to add a condition that when the number equals a certain number, like 50, it uses a different substition.

For example if match equals 50:

use

rep = "<p> \\1 </p>"

instead of

rep = "<div> \\1 </div>"
1
  • First get the matched digits then based in its value call next regex to replaced it with desired one. Commented Jun 24, 2014 at 18:20

2 Answers 2

3

Yes you can use a function as replacement and do the conditional checks there:

def check(match):
    g = match.group(1) # group(1) or any group number you have
    if g == '50':
        return '<p>%s</p>' % g
    else:
        return '<div>%s</div>' % g

res = re.sub(pat, check, value)
Sign up to request clarification or add additional context in comments.

Comments

2

You can use a function instead of a replacement pattern in re.sub. The function will be passed the match object. So for example:

re.sub(r'(\d+)', lambda m: "-" + m.group(0) + "-" if m.group(0) != "50" else "*"+m.group(0)+"*", "a 50 b")
# gives 'a *50* b'
re.sub(r'(\d+)', lambda m: "-" + m.group(0) + "-" if m.group(0) != "50" else "*"+m.group(0)+"*", "a 64 b")
# gives 'a -64- b'

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.