Regex for partial path

Peter picture Peter · Oct 28, 2018 · Viewed 8k times · Source

I have paths like these (single lines):

/
/abc
/def/
/ghi/jkl
/mno/pqr/
/stu/vwx/yz
/abc/def/ghi/jkl

I just need patterns that match up to the third "/". In other words, paths containing just "/" and up to the first 2 directories. However, some of my directories end with a "/" and some don't. So the result I want is:

/
/abc
/def/
/ghi/jkl
/mno/pqr/
/stu/vwx/
/abc/def/

So far, I've tried (\/|.*\/) but this doesn't get the path ending without a "/".

Answer

slartidan picture slartidan · Oct 28, 2018

I would recommend this pattern:

/^(\/[^\/]+){0,2}\/?$/gm

DEMO

It works like this:

  • ^ searches for the beginning of a line
  • (\/[^\/]+) searches for a path element
    • ( starts a group
    • \/ searches for a slash
    • [^\/]+ searches for some non-slash characters
  • {0,2} says, that 0 to 2 of those path elements should be found
  • \/? allows trailling slashes
  • $ searches for the end of the line

Use these modifiers:

  • g to search for several matches within the input
  • m to treat every line as a separate input