且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Perl 中替换特定的捕获组而不是整个正则表达式

更新时间:2022-11-12 09:24:17

如果您只需要替换一个捕获,那么使用 @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"