perl 正则表达式替换中的条件

编程入门 行业动态 更新时间:2024-10-23 12:33:30
本文介绍了perl 正则表达式替换中的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果匹配一组,我正在尝试使用 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 正则表达式替换中的条件

    本文发布于:2023-06-05 19:41:08,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/526444.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:条件   正则表达式   perl

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!