【问题标题】:Regex (PHP flavour) to match over multiplie lines OR not multiple lines正则表达式(PHP 风格)匹配多行或不匹配多行
【发布时间】:2016-01-29 11:17:11
【问题描述】:

我正在研究一个匹配以下两种语法的正则表达式...

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 新手)有什么想法吗? 第 2 行和第 3 行的开头有空格,语法片段 1 但没有显示以真正了解语法的呈现方式,请查看下面的 Regex101 链接。谢谢!

这里是 Regex101...

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

【问题讨论】:

  • 我编辑了问题,使示例字符串看起来与 regex101.com 中的相同。如果空格真的可以是任何空间,并且可以有任何数量的空间,我会投票支持我的答案:)

标签: php regex multiline


【解决方案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\+

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

【讨论】:

  • 感谢您的意见!
【解决方案2】:

您可以将模式中的常规空格替换为与任何空格匹配的\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-typeaction-type 之前有一个或多个空格)
  • \s+start-stop\s+group\s+tacacs\+ - 匹配单词之间有 1 个或多个空格的 start-stop group tacacs+

【讨论】:

  • 请注意,要匹配所有 Unicode 空白,不要忘记在正则表达式的末尾添加 /u 修饰符:'~^aaa\s+accounting\s+system\s+default(?:\s+action-type)?\s+start-stop\s+group\s+tacacs\+~mu'
  • 很棒的东西,我也学到了一些东西!谢谢你的帮助!真的很感激。
  • 不客气。请注意,当我需要在我的模式中使用可选字符序列时(正如 Casimir 在他的回答中指出的那样),我也更喜欢 non-capturing groups? 量词应用于它们(如 (?:...)?)。
  • 再次感谢非捕获组链接帮助我很好地处理它
【解决方案3】:

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

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

否则:

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

RegEx Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多