REGEX – Match all the absolute path with more than one subfolder


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.

/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



  • ^ – 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,\}$.

Leave a ReplyCancel reply