javaregexparsingre2sumologic

Regex for partial path


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 "/".


Solution

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

    To break it down

    But I'll point out that the is almost always the wrong answer for directory matching. Some directories have special meaning, like /../.. which actually goes up two directories, not down. Better to use the systems directory API instead for more robust results.