0

I can't find solution how to extract specific part of a path when I have a glob pattern for it.

I have incoming file paths that look like this:

'src/features/gui/images/main/effects/lightning/1.png'

And I want to extract specific leading part of it (always beginning of a path):

'src/features/gui/images/main/'

And I have two incoming glob patterns (the patterns may change, but will always point to a directories and images inside them):

  1. 'src/features/*/images/*/'
  2. 'src/features/*/images/*/**/*.{png,jpg,gif}'

I would like to extract directory path that matches pattern #1 in incoming file paths.

My intuition tells me it should be trivial, but can't find a solution. I'm looking in a solution that operates only on strings (or regexp) and do not do additional glob searches on disk. I've searched various JS modules on NPM, but all what I've found only returns if path matches glob pattern, but not actual match substring.

HankMoody
  • 3,077
  • 1
  • 17
  • 38

1 Answers1

1

At least the first pattern is easy to translate to a regex (note that I'm assuming that the directory names in between contain only characters within the \w-metacharacter), which in turn allows you to easily obtain the required substring (in that case the capturing group at index 1):

const regex = /^.*(src\/features\/\w+\/images\/\w+\/).*$/gm;
const str = 'src/features/gui/images/main/effects/lightning/1.png';
const match = regex.exec(str)
console.log(match[1]); // prints src/features/gui/images/main/
eol
  • 23,236
  • 5
  • 46
  • 64
  • Thanks for your reply, but I forgot to mention in the question, that I don't want to hardcode anything about the glob patterns, because they are also given to me from outside. – HankMoody Jul 07 '20 at 19:01
  • Check this in that case: https://stackoverflow.com/questions/41112143/does-string-match-glob-pattern – eol Jul 07 '20 at 19:33
  • 1
    Thanks again! I ended up using minimatch module and the `makeRe()` method, which from a glob string creates regular expression. Then I needed to convert that regexp to string to be able to strip ^ and $ symbols and convert back to regexp, so it detects parts of a path. – HankMoody Jul 13 '20 at 17:05