如果匹配一组,我正在尝试使用 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)//'更多推荐
perl 正则表达式替换中的条件
发布评论