假设我有一个文件learning.txt,其中包含以下信息:
A *
B &
C (
D )
如何获取用户输入字符串abc
并返回*&(
答案 0 :(得分:1)
在Perl中有这种非常有效的(O(N + M))溶液
my %replace = ( A => '*', B => '&', C => '(', D => ')' );
my $re = join '|', map quotemeta, keys %replace;
$re = qr/($re)/;
# and somewhere else in the scope with $re and %replace
s/$re/$replace{$1}/g;
但是对于不区分大小写的情况,它有点复杂了
use feature qw(fc); # since v5.16 use lc otherwise
my %replace = ( A => '*', B => '&', C => '(', D => ')' );
my $re = join '|', map quotemeta, keys %replace;
$re = qr/($re)/i;
my %replace_fc;
@replace_fc{ map fc, keys %replace } = values %replace;
# and somewhere else in the scope with $re and %replace_fc
s/$re/$replace_fc{fc $1}/g;
只需从您的文件中提取%replace
while (<>) {
my ($key, $val) = split;
$replace{$key} = $val;
}
答案 1 :(得分:0)
使用/^(A|B|C)\\b\\s*(.+)/m
正则表达式(具有多行选项),然后连接第二组。
请参阅此正则表达式输出here的示例。