简体   繁体   中英

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.

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

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? Pulling my hair out! (I know it's probably simple but I'm a Regex newbie) Any ideas? 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. Thanks!

Here it is in Regex101...

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:

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

Or else:

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

RegEx Demo

You can replace the regular spaces in your pattern with \\s that matches any whitespace:

'~^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
  • aaa\\s+accounting\\s+system\\s+default - matches a sequence aaa accounting system default where \\s+ matches one or more whitespaces
  • (?:\\s+action-type)? - an optional action-type (with one or more whitespace before action-type )
  • \\s+start-stop\\s+group\\s+tacacs\\+ - matches start-stop group tacacs+ that have 1 or more spaces in between the words.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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