perl regex是什么_如何在Perl单行代码中使用Regex匹配多行

perl regex是什么

Perl one-liners with perl’s regular expression statement can be a very powerful text processing tools used as commands in a terminal or a script. By default, the input to the perl one-liner with -p or -n options is passed line by line. However, when we want to match multiple lines, it gets us some trouble. In this post we take a look at a technique to match multiple lines using Perl one-liner.

具有perl正则表达式语句的Perl单行代码可以是一种非常强大的文本处理工具,可用作终端或脚本中的命令。 缺省情况下,使用-p-n选项的perl单线输入是逐行传递的。 但是,当我们要匹配多行时,会给我们带来一些麻烦。 在本文中,我们将介绍一种使用Perl单线匹配多行的技术。

As an example, let’s try to find and remove content between <PRE> and </PRE> (both tags included too) if the content contains only new lines (\n), spaces, and <BR>/<HR> tags. A simple regex like <PRE>[\s{<BR>}{<HR>}]*</PRE> matches such criteria. But it does not match across multiple line (that is \s does not match \n). The trick here is to add option -0777 so that the record separator is the char of octal number 777 instead of \n.

例如,如果内容仅包含换行( \n ),空格和<BR> / <HR>标记,让我们尝试在<PRE></PRE> (还包括两个标记)之间查找和删除内容。 像<PRE>[\s{<BR>}{<HR>}]*</PRE>这样的简单正则表达式可以匹配这些条件。 但是它与多行不匹配(即\s\n不匹配)。 这里的技巧是添加选项-0777以便记录分隔符是八进制数777的char而不是\n

perl -0777 -pe 's|<PRE>[\s{<BR>}{<HR>}]*</PRE>||g'

You can find the meanings of the options to perl used here from perlrun manual.

您可以从perlrun手册中找到此处使用的perl选项的含义。

Here is one example of usages of the above one-liner.

这是上述单线的用法的一个示例。

$ echo -e "text\n<PRE>\n<BR>\n<HR><HR>\n \n</PRE>more text"
text
<PRE>
<BR>
<HR><HR>

</PRE>more text
$ echo -e "text\n<PRE>\n<BR>\n<HR><HR>\n \n</PRE>more text" |
perl -0777 -pe 's|<PRE>[\s{<BR>}{<HR>}]*</PRE>||g'
text
more text

The same technique can be used for grep too: How to Grep 2 Lines using grep in Linux.

相同的技术也可以用于grep如何在Linux中使用grep对2行进行Grep

翻译自: https://www.systutorials.com/how-to-match-multiple-lines-using-regex-in-perl-one-liners/

perl regex是什么

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值