初学者正则表达式:多次替换 [英] Beginner Regex: Multiple Replaces
本文介绍了初学者正则表达式:多次替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串:
$mystring = "My cat likes to eat tomatoes.";
我想用正则表达式对这个字符串进行两次替换.我想做s/cat/dog/
和s/tomatoes/pasta/
.但是,我不知道如何正确格式化正则表达式以在一个表达式、一行、一个声明中进行多次替换.现在,我只有:
I want to do two replacements on this string with regex. I want to do s/cat/dog/
and s/tomatoes/pasta/
. However, I don't know how to properly format the regular expression to do the multiple replacements in one expression, on one line, in one declaration. Right now, all I have is:
$mystring =~ s/cat/dog/ig;
$mystring =~ s/tomatoes/pasta/ig;
推荐答案
我的建议是你这样做
my $text = 'My cat likes to eat tomatoes.';
my ( $format = $text ) =~ s/\b(cat|tomatoes)\b/%s/g;
然后你可以这样做:
my $new_sentence = sprintf( $format, 'dog', 'pasta' );
还有这个:
$new_sentence = sprintf( $format, 'tiger', 'asparagus' );
我和其他人一起去.您不应该希望在一个表达式或一行中完成所有操作……但这里有一种方法:
I go with the others. You shouldn't want to do it all in one expression, or one line...but here is a way:
$text =~ s/\b(cat|tomatoes)\b/ ${{ qw<cat dog tomatoes pasta> }}{$1} /ge;
这篇关于初学者正则表达式:多次替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文