假设我们想从
我有猫,猫和猫,她有狗,狗和狗。
至
我有狗,狗和狗,而她有猫,猫和猫。
当然,可以用多个regex来完成:
s/cat/monkey/g
s/dog/cat/g
s/monkey/dog/g所以问题是它是否可以用one regex来完成。
发布于 2016-01-13 17:17:50
Perl解决方案
您可以使用替换定义哈希,并使用带有e修饰符的regex将反向引用传递给代码。
#!/usr/bin/perl
%data = ('cat', 'dog', 'dog', 'cat');
$x = "I have cat, cat and cat and she has dog, dog and dog.";
$x =~ s/\b(dog|cat)\b/$data{$1}/eg;
print $x;IDEONE演示:I have dog, dog and dog and she has cat, cat and cat.的输出
使用Notepad++的原始答案
如果计划使用Notepad++,可以使用带有条件替换模式的命名捕获组:
成本- \b(?<o1>dog)|(?<o2>cat)\b
替换为:(?{o1}cat:dog)

正则表达式将只匹配整个单词dog或cat,并根据匹配的组使用适当的替换。
这可能是因为在Notepad++中使用Boost regex库。
发布于 2016-01-13 17:12:39
在.NET中,您将这样做:
var regex = new Regex(@"(cat|dog)");
var text = regex.Replace(template,
match => match.Value=="cat"?"dog":"cat");https://stackoverflow.com/questions/34772742
复制相似问题