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 to get top parent directory without /

Looking for a regex given a path/to/filename.ext I want to determine the topmost parent path.

examples:
‘foo/bar/baz/file.ext’
‘file2.ext’
‘fooz/file3.ext’

should return ‘foo’ and ‘fooz’

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

Language used is groovy.

>Solution :

In general, the proper way to extract components of a pathname is to use tools designed for just that; in the case of Groovy, that would be java.nio.file.Path and @tim_yates‘s answer.

But the asker requested a regular-expression-based solution, so here is one:

pat = ~'^[^/]*(?=/)'
for (str in ['foo/bar/baz/file.ext', 'file2.ext', 'fooz/file3.ext']) {
  print str + ': '
  if (m = str =~ pat) {
    println '"'+m[0]+'"'
  } else {
    println 'NONE'
  }
}

Which outputs this:

foo/bar/baz/file.ext: "foo"
file2.ext: NONE
fooz/file3.ext: "fooz"

The pattern ^[^/]* matches a (longest-possible) sequence of zero or more (*) non-slash characters ([^/]) starting at the beginning of the line (^).

That would be enough by itself, except for the requirement that a string such as file2.ext, with no slashes at all, not match. The lookahead assertion (?=/) causes the pattern to match only if the matched text is followed by a slash.

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