在 Perl 中替换特定的捕获组而不是整个正则表达式 [英] Replace specific capture group instead of entire regex in Perl

查看:63
本文介绍了在 Perl 中替换特定的捕获组而不是整个正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有捕获组的正则表达式,可以在更广泛的上下文中匹配我想要的内容.然后我获取捕获组 $1 并将其用于我的需要.这很容易.

但是当我只想替换 $1 的内容而不是整个正则表达式时,如何使用带有 s/// 的捕获组?>

谢谢!
-f

解决方案

如果您只需要替换一个捕获,那么使用 @LAST_MATCH_START@LAST_MATCH_END(与 使用英语;参见perldoc perlvar) 和substr 可能是一个可行的选择:

使用英文 qw(-no_match_vars);$your_string =~ m/aaa (bbb) ccc/;substr $your_string, $LAST_MATCH_START[1], $LAST_MATCH_END[1] - $LAST_MATCH_START[1], "新内容";# 用新内容"替换bbb"

I've got a regular expression with capture groups that matches what I want in a broader context. I then take capture group $1 and use it for my needs. That's easy.

But how do use capture groups with s/// when I just want to replace the content of $1, not the entire regex, with my replacement?

Thanks!
–f

解决方案

If you only need to replace one capture then using @LAST_MATCH_START and @LAST_MATCH_END (with use English; see perldoc perlvar) together with substr might be a viable choice:

use English qw(-no_match_vars);
$your_string =~ m/aaa (bbb) ccc/;
substr $your_string, $LAST_MATCH_START[1], $LAST_MATCH_END[1] - $LAST_MATCH_START[1], "new content";
# replaces "bbb" with "new content"

这篇关于在 Perl 中替换特定的捕获组而不是整个正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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