在 Python 中的 re.sub 中获取组匹配 [英] Get Group Match in re.sub in Python

查看:82
本文介绍了在 Python 中的 re.sub 中获取组匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 中,我可以同时进行替换和捕获小组比赛.例如

In Perl, it is possible for me to do a substitution and capture a group match at the same time. e.g.

my $string = "abcdef123";
$string =~ s/(\d+)//;
my $groupMatched = $1; # $groupMatched is 123

在 Python 中,我可以使用 re.sub 函数进行替换,如下所示.但是,我无法找到一种方法来捕获 \d+ 组匹配而不调用另一个函数 re.match 并执行附加操作.

In Python, I can do the substitution using re.sub function as follows. However, I cannot find a way to capture the \d+ group match without invoking another function re.match and performing an additional operation.

string = "abcdef123"
string = re.sub("(\d+)", "", string)

有谁知道我如何从同一个 re.sub 操作中捕获\d+"匹配值作为单独的变量?我尝试了以下命令,但它不起作用.

Does anyone know how I can capture the "\d+" matched value as a separate variable from the same re.sub operation? I tried the following command and it doesn't work.

print r'\1'

推荐答案

你可以欺骗并传递一个函数给 re.sub:

You can cheat and pass a function to re.sub:

results = []
def capture_and_kill(match):
    results.append(match)
    return ""
string = "abcdef123"
string = re.sub("(\d+)", capture_and_kill, string)
results[0].group(1)
# => '123'

这篇关于在 Python 中的 re.sub 中获取组匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆