Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.
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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading