2

I want to extract the string between last two string using a regular expression. I cannot seem to be able to come up with the right expression, if someone could help me that would be great.

Say the string is: aa/bbbb/ccccc/eeee/fffff.jpg, I want to extract out "eeee".

Thank you.

2
  • regex101.com/r/aV9lK1/1 ?? Capturing a named group can help to name your required data. Commented Apr 11, 2016 at 23:58
  • 2
    Pretty decent @shafaq -- but definitely do not assume a 3-character extension — no extension is legal, .html and .properties are legal. How about /.*\/([^/]*)\/[^/]*/ Commented Apr 12, 2016 at 0:14

2 Answers 2

4

Since you only care about the last set of slashes, you start by matching anything
.*
then you want a literal slash
\/ (escaped since the slash would terminate the js regex)
now you want anything up to the next slash, which implies not a slash and _there must be something (one-or-more) and we'll put that in a capturing group so you can extract it.
([^/]+)
and followed by another literal slash
\/
then anything else (the file name?) that, again, does not include slashes
[^/]+

Putting that all together gives you the regex
/.*\/([^/]+)\/[^/]+/
and
"aa/bbbb/ccccc/eeee/fffff.jpg".match(/.*\/([^/]+)\/[^/]+/);
produces
["aa/bbbb/ccccc/eeee/fffff.jpg", "eeee"]
... the eeee is captured.

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

Comments

4

I know you said you wanted to use a regex but for those looking for a solution but don't require it to be a regex, you could do this simply by splitting the string:

 var originalString = 'aa/bbbb/ccccc/eeee/fffff.jpg';

 //convert to array
 var parts = originalString.split('/');

 //find the second to last item
 var lastPartOfPath = '';

 //make sure there are more than one part
 if (parts.length > 1) {
      lastPartOfPath = parts[parts.length-2];
 }

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.