我有一个字符串“Alex 28”。现在,我想提取数字 28 并使用正则表达式将其加 2。
在 Perl 中,我可以这样得到它:
#!/usr/bin/perl
use strict;
use warnings;
my $str='Alex 28';
$str=~s/(\d+)/$1+2/e;
为了在 Python 中实现这一点,我尝试了以下方法:
#!/usr/bin/python
import re
str = 'Alex 28'
match=re.sub(r'(\d+)',r'\g<1>',str)
如何将 2 添加到“\g<1>
” ' 哪个已被提取?我尝试使用 int 函数,它不起作用。请帮忙。
版本:Python 2.7.3
最佳答案
您可以通过supplying a function to the repl
argument 使用re.sub
:
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.
例如:
def add_two(match):
return str(int(match.group()) + 2)
s = 'Alex 28'
re.sub(r'(\d+)', add_two, s)
或者,使用 lambda:
re.sub(r'(\d+)', lambda m: str(int(m.group()) + 2), s)
请注意:
- 使用
str
作为变量名是一个糟糕的选择,因为它会覆盖内置的str
- 替换仅适用于字符串,因此作为
repl
参数传递的函数应该返回一个字符串 - 我使用了返回整个匹配项的
match.group()
:如果正则表达式定义了多个组,您可能需要指定组索引。
关于python - 如何评估 re.sub 中的替换零件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15428116/