perl 正则表达式替换中的条件 [英] Conditional in perl regex replacement
问题描述
如果匹配一组,我正在尝试使用 perl regex one-liner 返回不同的替换结果.到目前为止,我已经有了这个:
I'm trying to return different replacement results with a perl regex one-liner if it matches a group. So far I've got this:
echo abcd | perl -pe "s/(ab)(cd)?/defined($2)?\1\2:''/e"
但我明白
Backslash found where operator expected at -e line 1, near "1\"
(Missing operator before \?)
syntax error at -e line 1, near "1\"
Execution of -e aborted due to compilation errors.
如果输入是 abcd
我想得到 abcd
,如果它是 ab
我想得到一个空字符串.我哪里出错了?
If the input is abcd
I want to get abcd
out, if it's ab
I want to get an empty string. Where am I going wrong here?
推荐答案
您使用了正则表达式原子 \1
和 \2
(匹配第一个或第二个捕获捕获的内容)在正则表达式模式之外.您打算使用 $1
和 $2
(就像您在另一个地方所做的那样).
You used regex atoms \1
and \2
(match what the first or second capture captured) outside of a regex pattern. You meant to use $1
and $2
(as you did in another spot).
此外,双引号字符串中的美元符号对您的外壳有意义.最好在程序周围使用单引号[1].
Further more, dollar signs inside double-quoted strings have meaning to your shell. It's best to use single quotes around your program[1].
echo abcd | perl -pe's/(ab)(cd)?/defined($2)?$1.$2:""/e'
更简单:
echo abcd | perl -pe's/(ab(cd)?)/defined($2)?$1:""/e'
更简单:
echo abcd | perl -pe's/ab(?!cd)//'
<小时>
- 避免在程序中使用单引号[2],或者使用
'\''
来转义"它们. - 您通常可以使用
q{}
而不是单引号.您也可以切换到使用双引号.在双引号内,您可以使用\x27
作为撇号.
- Either avoid single-quotes in your program[2], or use
'\''
to "escape" them. - You can usually use
q{}
instead of single-quotes. You can also switch to using double-quotes. Inside of double-quotes, you can use\x27
for an apostrophe.
这篇关于perl 正则表达式替换中的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!