正则表达式(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 link。谢谢!

在 Regex101 中...

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

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

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

否则:

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

RegEx Demo

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

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

regex demo

此外,我还做了一些其他优化,以便您的两种类型的字符串可以匹配:

  • ^ - 匹配行首(由于 /m)修饰符
  • aaa\s+accounting\s+system\s+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+

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

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

您可以使用非捕获组 (?:...) 和可选量词 ?:

以更好的方式编写它
^aaa accounting system default(?:\n action-type)? start-stop\n? group tacacs\+

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