Jis van Overschot
Jis van Overschot

Reputation: 101

How to match file extension of file on specific path with regex?

I'm trying to match the file extension of multiple file paths with the same directory but not from other directories.

Here are two file paths I encounter.

Path I want to match:

url: "#/dist/js/core/filename.js",

Path I don't want to match:

url: "#/assets/knockout/filename.js",

What I'm trying to do is select .js when the file path is equal to /dist/js/core/.

I don't seem to find any way to account for the file name that is different every time.

I have tried using positive lookbehind but this will not account for the file name and you can't use a lookbehind with someting like .+ because it has a non-fixed width.

(?<=dist\/js\/core\/)\.js

Upvotes: 0

Views: 2026

Answers (2)

Jis van Overschot
Jis van Overschot

Reputation: 101

I found a regex that will work form this regex will work for me.

(?<=dist\/js\/core\/.+)\.js

Pretty stupid, on regex101.com I forgot to switch from PCRE to ECMAScript. So i got the error that I can't use .+ in a lookbehinde because it doesn't have a fixed width.

Thanks for the quick replies!

Upvotes: 2

adelriosantiago
adelriosantiago

Reputation: 8124

You can use this regex: /(?<!(knockout|not_this|or_this).*)[a-zA-z0-9-_]+\.js/gm

It looks heavy but it is in fact very simple, it will basically:

  1. (?<!(knockout|not_this|or_this).*): Ensure that "knockout" or "not _this" or "or_this" are not present before the rest of the regex.
  2. [a-zA-z0-9-_]+\.js/gm: Look for a valid filename that ends with ".js"

Demo: https://regex101.com/r/PLzO41/1

Upvotes: 0

Related Questions