繁体   English   中英

正则表达式(PHP风格)以匹配多行或不多行

[英]Regex (PHP flavour) to match over multiplie lines OR not multiple lines

我正在研究一种正则表达式,该正则表达式将同时符合以下两个语法...

1。

aaa accounting system default  
 action-type start-stop  
 group tacacs+

2。

aaa accounting system default start-stop group tacacs+

到目前为止我最好的是...

^aaa accounting system default (\\n action-type |)start-stop(\\n |) group tacacs\\+

上面的正则表达式将匹配语法编号2而不匹配1? 拉我的头发! (我知道这可能很简单,但我是Regex新手)有什么想法吗? 在语法段号1的第2行和第3行的开头有空格,但是没有显示出来以使您真正了解语法的呈现方式,请查看下面的Regex101链接。 谢谢!

在Regex101中...

https://regex101.com/r/lW8hT1/1

它不起作用,因为可选组中有多余的空格:

^aaa accounting system default(\n action-type|) start-stop(\n|) group tacacs\+

您可以使用非捕获组(?:...)和可选的量词?更好地编写它?

^aaa accounting system default(?:\n action-type)? start-stop\n? group tacacs\+

(这样可以避免无用的捕获)

要跨多行匹配,您将需要DOTALL标志:

/(?s)\baaa accounting system default.*?group tacacs\+/

要不然:

/\baaa accounting system default.*?group tacacs\+/s

正则演示

您可以将\\s中的常规空格替换为与任何空格匹配的\\s

'~^aaa\s+accounting\s+system\s+default(?:\s+action-type)?\s+start-stop\s+group\s+tacacs\+~m'

正则表达式演示

另外,我进行了一些其他优化,以便可以匹配两种类型的字符串:

  • ^ -匹配行首(由于/m
  • aaa\\s+accounting\\s+system\\s+default aaa accounting system default匹配序列aaa accounting system default ,其中\\s+匹配一个或多个空格
  • (?:\\s+action-type)? -可选的action-type (在action-type之前有一个或多个空格)
  • \\s+start-stop\\s+group\\s+tacacs\\+ -匹配单词之间有1个或多个空格的start-stop group tacacs+

暂无
暂无

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

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