Tuesday, 15 March 2011

Conditional Regex Substition in Python -



Conditional Regex Substition in Python -

i have regex this

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

but want add together status when number equals number, 50, uses different substition.

for illustration if match equals 50:

use

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

instead of

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

yes can utilize function replacement , conditional checks there:

def check(match): g = match.group(1) # group(1) or grouping number have if g == '50': homecoming '<p>%s</p>' % g else: homecoming '<div>%s</div>' % g res = re.sub(pat, check, value)

python regex

No comments:

Post a Comment