[英]Regex (PHP flavour) to match over multiplie lines OR not multiple lines
I working on a Regex that'll match both the following pieces of syntax... 我正在研究一种正则表达式,该正则表达式将同时符合以下两个语法...
1. 1。
aaa accounting system default
action-type start-stop
group tacacs+
2. 2。
aaa accounting system default start-stop group tacacs+
The best I've got so far is... 到目前为止我最好的是...
^aaa accounting system default (\\n action-type |)start-stop(\\n |) group tacacs\\+
The above Regex will match syntax number 2 but not 1? 上面的正则表达式将匹配语法编号2而不匹配1? Pulling my hair out! 拉我的头发! (I know it's probably simple but I'm a Regex newbie) Any ideas? (我知道这可能很简单,但我是Regex新手)有什么想法吗? There are spaces at the beginning of lines 2 & 3 in syntax piece number 1 but aren't being displayed to get a real look at how the syntax is presented take a look at the below Regex101 link. 在语法段号1的第2行和第3行的开头有空格,但是没有显示出来以使您真正了解语法的呈现方式,请查看下面的Regex101链接。 Thanks! 谢谢!
Here it is in Regex101... 在Regex101中...
https://regex101.com/r/lW8hT1/1 https://regex101.com/r/lW8hT1/1
It doesn't work because you have redundant spaces in your optional groups: 它不起作用,因为可选组中有多余的空格:
^aaa accounting system default(\n action-type|) start-stop(\n|) group tacacs\+
You can write it in a better way using non-capturing groups (?:...)
and the optional quantifier ?
您可以使用非捕获组(?:...)
和可选的量词?
更好地编写它?
: :
^aaa accounting system default(?:\n action-type)? start-stop\n? group tacacs\+
(in this way you avoid useless captures) (这样可以避免无用的捕获)
To match across multiple line you will need DOTALL
flag: 要跨多行匹配,您将需要DOTALL
标志:
/(?s)\baaa accounting system default.*?group tacacs\+/
Or else: 要不然:
/\baaa accounting system default.*?group tacacs\+/s
You can replace the regular spaces in your pattern with \\s
that matches any whitespace: 您可以将\\s
中的常规空格替换为与任何空格匹配的\\s
:
'~^aaa\s+accounting\s+system\s+default(?:\s+action-type)?\s+start-stop\s+group\s+tacacs\+~m'
See the regex demo 见正则表达式演示
Also, I made some other optimizations so that your two types of strings could be matched: 另外,我进行了一些其他优化,以便可以匹配两种类型的字符串:
^
- matches start of a line (due to /m
) modifier ^
-匹配行首(由于/m
) aaa\\s+accounting\\s+system\\s+default
- matches a sequence aaa accounting system default
where \\s+
matches one or more whitespaces aaa\\s+accounting\\s+system\\s+default
aaa accounting system default
匹配序列aaa accounting system default
,其中\\s+
匹配一个或多个空格 (?:\\s+action-type)?
- an optional action-type
(with one or more whitespace before action-type
) -可选的action-type
(在action-type
之前有一个或多个空格) \\s+start-stop\\s+group\\s+tacacs\\+
- matches start-stop group tacacs+
that have 1 or more spaces in between the words. \\s+start-stop\\s+group\\s+tacacs\\+
-匹配单词之间有1个或多个空格的start-stop group tacacs+
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.