0

I need a regular expression to match many specific paths/strings but I can't figure it out.

E.g.

../foo/hoo/something.js -> Needs to match ../foo/hoo/

../foo/bar/somethingElse.js -> Needs to match ../foo/bar/

../foo/something-else.js -> Needs to match ../foo/

What I tried with no luck is the following regex:

/\..\/foo\/|bar\/|hoo\//g
2
  • What's the key? In first two you want to match both dirs, in the third one dir and filename... Commented Dec 12, 2017 at 8:56
  • Thanks for your comment I miss-typed my case. The case is as shown in updated answer. Commented Dec 12, 2017 at 8:58

3 Answers 3

1

This should work out for you:

/(\.\.\/foo\/(hoo\/|bar\/)?)/

https://regex101.com/r/1aTf7y/1

So you select ../foo/ at first and then have a group that can either contain hoo/ or bar/. And the question mark allows 0 or one instances.

If you want to be a little less specific, you could also do

/(\.\.\/[^\/]+\/(hoo\/|bar\/)?)/

The [^\/]+ allows all characters except for a slash

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the regex

(\/[^\/\s]+)+(?=\/)

see the regex101 demo

function match(str){
  console.log(str.match(/(\/[^\/\s]+)+(?=\/)/)[0]);
}

match('./foo/hoo/something.js');
match('../foo/bar/somethingElse.js');
match('../foo/something-else.js');

1 Comment

This also matches strings which do not start from '../foo'
0

This should be the regex for matching all dirs without filename.

 /^(.*[/])[^/]+$/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.