i have a series of string representing disks on a file system.
I would like to match all the strings with more than one subfolder.
Ex:
/dev/sda1 (no match)
/ (no match)
/dev (no match)
/dev/mapper/usr (match)
/dev/test/local (match)
I’ve tried something like:
^\/[^\/]+\/[^\/]+\/[^\/]+$
But would like to have something more generic that matches all the strings that have this pattern /.*
more than twice. Is there a more elegant way to approach this ?
>Solution :
You can use
^(\/[^\/]+){3,}$
Details:
^
– start of string(\/[^\/]+){3,}
– three or more sequences of a/
char followed with one or more (but as many as possible) chars other than/
$
– string end.
See the regex demo.
NOTE: The pattern above is POSIX ERE and PCRE compliant. When possible, in non-POSIX regex flavors, it is best to use non-capturing groups when you only use a grouping construct to quantify a pattern sequence. So, if you were to use it in JavaScript, I’d recommend using /^(?:\/[^\/]+){3,}$/
. Also, if you even need to use it in POSIX BRE, you’d need ^\(\/[^\/]\{1,\}\)\{3,\}$
.