我可以在 VIM 或 Perl 的单个正则表达式中替换多个项目吗? [英] Can I substitute multiple items in a single regular expression in VIM or Perl?

查看:20
本文介绍了我可以在 VIM 或 Perl 的单个正则表达式中替换多个项目吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有字符串The quick brown fox jumps over the lazy dog",我可以用一个正则表达式将其更改为The slow brown fox jumps over the energy dog"吗?目前,我针对这种情况使用了两组正则表达式.(在本例中,我使用 s/quick/slow/ 后跟 s/lazy/energetic/.)

Let's say I have string "The quick brown fox jumps over the lazy dog" can I change this to "The slow brown fox jumps over the energetic dog" with one regular expression? Currently, I use two sets of regular expressions for this situation. (In this case, I use s/quick/slow/ followed by s/lazy/energetic/.)

推荐答案

替换的第二部分是双引号字符串,因此可以发生任何正常的插值.这意味着您可以使用捕获的值来索引到散列中:

The second part of a substitution is a double quoted string, so any normal interpolation can occur. This means you can use the value of the capture to index into a hash:

#!/usr/bin/perl

use strict;
use warnings;


my %replace = (
    quick => "slow",
    lazy  => "energetic",
);

my $regex = join "|", keys %replace;
$regex = qr/$regex/;

my $s = "The quick brown fox jumps over the lazy dog";

$s =~ s/($regex)/$replace{$1}/g;

print "$s
";

这篇关于我可以在 VIM 或 Perl 的单个正则表达式中替换多个项目吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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