Reputation: 16984
I have a string say 'Alex 28'. Now, I want to extract the number 28 and add it by 2 using regex.
In Perl, I could have got it like this:
#!/usr/bin/perl
use strict;
use warnings;
my $str='Alex 28';
$str=~s/(\d+)/$1+2/e;
To achieve this in Python, I tried the below:
#!/usr/bin/python
import re
str = 'Alex 28'
match=re.sub(r'(\d+)',r'\g<1>',str)
How do I add 2 to the '\g<1>
' which has been fetched? I tried using int function, it is not working. Please help.
Version: Python 2.7.3
Upvotes: 1
Views: 1795
Reputation: 76755
You can use re.sub
by supplying a function to the repl
argument:
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
For example:
def add_two(match):
return str(int(match.group()) + 2)
s = 'Alex 28'
re.sub(r'(\d+)', add_two, s)
Or, using a lambda:
re.sub(r'(\d+)', lambda m: str(int(m.group()) + 2), s)
Please note that:
str
as a variable name is a bad choice as it overrides the builtin str
repl
argument should return a stringmatch.group()
which returns the whole match: you may need the specify the group index if the regex defines multiple groups.Upvotes: 5