简体   繁体   English

Perl - 用正则表达式上的任意操作替换正则表达式匹配

[英]Perl - replace regex match with arbitrary operation on regex

I have the following line in my Perl script: 我的Perl脚本中有以下行:

s/\b(\w+)\b/ $replaces{$1} ? $replaces{$1} : $1 /g;

I want to find all words in the string and if the word is in the array of known words replace it else keep it (ideally I want to do an arbitrary operation on match, not just ternary operator). 我想找到字符串中的所有单词,如果单词在已知单词的数组中,则替换它,否则保留它(理想情况下我想在匹配上执行任意操作,而不仅仅是三元运算符)。

To do so I attempt to use ternary operator. 为此,我尝试使用三元运算符。 Perl treats ? Perl对待? and : as literal symbol and just concats these with variables (if defined). 和:作为文字符号,只使用变量(如果已定义)将它们连接起来。

How do I cause Perl to treat ?: inside the replace as ternary operator? 如何让Perl处理?:在replace中作为三元运算符?

PS: I know that I can just perform operation on match in the next line of code but I want to keep it one liner for clarity. PS:我知道我可以在下一行代码中对匹配执行操作,但为了清晰起见,我想保留一个衬里。

你需要'e'(执行)限定符:

s/\b(\w+)\b/ $replaces{$1} ? $replaces{$1} : $1 /ge;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM