我可以在VIM或Perl中的单个正则表达式中替换多个项目吗? [英] Can I substitute multiple items in a single regular expression in VIM or Perl?
本文介绍了我可以在VIM或Perl中的单个正则表达式中替换多个项目吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我有一个字符串快速的棕色狐狸跳过懒惰的狗",我可以将其更改为带有一个正则表达式的缓慢的棕色狐狸跳过充满活力的狗"吗?目前,我针对这种情况使用了两组正则表达式. (在这种情况下,我先使用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\n";
这篇关于我可以在VIM或Perl中的单个正则表达式中替换多个项目吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文