python - 如何评估 re.sub 中的替换零件?

标签 python regex

我有一个字符串“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/

相关文章:

python - 将字符串中的日期列表转换为 Python 中的月、日、年

python - wpa-handshake with python - 散列困难

python - 尝试从 python 3.5 中的 pyspark.sql.functions 导入 col 时未解析的引用

python - 元素的选择器(CSS 或 Xpath)

python - 我应该如何使用 pandas 读取没有 'unnamed' 行的 csv 文件?

c# - 用于解析函数和参数的正则表达式

regex - 在 VBA 中使用正则表达式拆分块

regex - inputFormatter 应该只允许十进制数和负数

regex - 如何在 Nginx 服务器上执行不区分大小写的正则表达式?

python - 用正则表达式替换文本