在 perl 中使用单个正则表达式进行多次替换 [英] Multiple substitutions with a single regular expression in perl

查看:71
本文介绍了在 perl 中使用单个正则表达式进行多次替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 perl 中有以下内容:

Say I have the following in perl:

my $string;
$string =~ s/ /\\ /g;
$string =~ s/'/\\'/g;
$string =~ s/`/\\`/g;

可以用一个组合的正则表达式而不是 3 个单独的正则表达式来执行上述替换吗?

Can the above substitutions be performed with a single combined regular expression instead of 3 separate ones?

推荐答案

$string =~ s/([ '`])/\\$1/g;

使用 字符类 [ '`] 来匹配空格、' 或 ` 之一,并使用括号 () 来记住匹配的字符.$1 然后用于在替换中包含记住的字符.

Uses a character class [ '`] to match one of space, ' or ` and uses brackets () to remember the matched character. $1 is then used to include the remembered character in the replacement.

这篇关于在 perl 中使用单个正则表达式进行多次替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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