Regex 带有匹配和替换字符串中相应管道的正则表达式

Regex 带有匹配和替换字符串中相应管道的正则表达式,regex,matlab,Regex,Matlab,是否可以在正则表达式替换的匹配和替换字符串中使用相应的或运算符(|),从而用不同替换字符串的对应列表替换不同可能匹配的列表?比如说, perl -e '$str="word1"; $str=~s/1/2/; print $str."\n"' word2 perl -e '$str="word3"; $str=~s/3/4/; print $str."\n"' word4 perl -e '$str="word1"; $str=~s/1|3/2|4/; print $str."\n"'

是否可以在正则表达式替换的匹配和替换字符串中使用相应的
运算符(
|
),从而用不同替换字符串的对应列表替换不同可能匹配的列表?比如说,

perl -e '$str="word1"; $str=~s/1/2/; print $str."\n"'
  word2
perl -e '$str="word3"; $str=~s/3/4/; print $str."\n"'
  word4

perl -e '$str="word1"; $str=~s/1|3/2|4/; print $str."\n"'
  word2          (actual output: word2|4)
perl -e '$str="word3"; $str=~s/1|3/2|4/; print $str."\n"'
  word4          (actual output: word2|4)

最后两条语句给出了虚构的(期望的)输出(实际输出显示在括号中)。

归用户的积分mu太短了

使用多个匹配输入模式和输出字符串的正则表达式替换在Matlab中实现,如下例所示

str_match = cell(2,1); str_match{1}='1'; str_match{2}='3';
str_sub = cell(2,1); str_sub{1}='2'; str_sub{2}='4';
regexprep('word1',str_match,str_sub)
    ans = word2
regexprep('word3',str_match,str_sub)
    ans = word4

我对Matlab不够熟悉,无法给你任何可靠的答案,但子弹3可能很有趣:它没有意义。为了得到第二个,你对前两个做了什么?谢谢@muistooshort。顺便说一下,你对其他语言的建议非常好。@Phonon:user001正在寻找Perl的
%m=(1=>2,3=>4)的Matlab版本$s=“word1”$s=~s/1 | 3/$m{$&}/
或Ruby的
m={'1'=>'2','3'=>'4'};'word1'.gsub(/1 | 2/){m[$&]}
或JavaScript的
m={1:2,3:4};'替换(/1 | 2/,函数(x){返回m[x]})继续,把它作为你自己的答案(你可以回答你自己的问题并接受这些答案),我不介意,我只是很高兴看到问题解决了。