admin管理员组

文章数量:1421046

I have a regex that looks like the following currently:

/^.*[\\\/]/

This will strip every single backslash from a string. The problem I'm facing is I have to now be able to capture everything from the second to last backslash.

Example:

/Users/foo/a/b/c would return b/c /Another/example/ would return Another/Example

So I need to capture everything after the second to last backslash. How would the regex above do that?

I have a regex that looks like the following currently:

/^.*[\\\/]/

This will strip every single backslash from a string. The problem I'm facing is I have to now be able to capture everything from the second to last backslash.

Example:

/Users/foo/a/b/c would return b/c /Another/example/ would return Another/Example

So I need to capture everything after the second to last backslash. How would the regex above do that?

Share Improve this question asked Feb 7, 2017 at 0:28 randombitsrandombits 48.6k79 gold badges273 silver badges449 bronze badges 4
  • Wouldn't you want to get a/b from your first example if you're capturing everything around the second-to-last backslash? Not super-clear... – Nightfirecat Commented Feb 7, 2017 at 0:32
  • are your urls/strings consistently employing trailing slashes? or should they be ignored? – haxxxton Commented Feb 7, 2017 at 0:39
  • @haxxxton they can actually be ignored. – randombits Commented Feb 7, 2017 at 0:41
  • can we assume that the characters between the / are word characters (ie. [a-zA-Z0-9_]) are there other characters that need to be acmodated for (e.g. $-_.+!*'(),)? – haxxxton Commented Feb 7, 2017 at 1:08
Add a ment  | 

3 Answers 3

Reset to default 8

Try with this simple solution:

s = "aaaa/bbbb/cccc/dddd";
s.split("/").slice(-2).join("/"); /* It will return "cccc/dddd" */

I assume that you mean forward slash, not backslash.

Here is a regex alternative to pierlauro's answer.

/([^\/]+\/[^\/]+)\/?$/

Regex101

As pierlauro's answer shows, split, join, and slice are probably the best options for this. But if you MUST use a regex (not sure why), you could employ something like the following:

\/?(\[^\/\]+?\/\[^\/\]+)\/?$

This regex acmodates for optional trailing slashes and for urls shorter than 2 /s. It leverages the $ character to focus our search scope on the end of the string.

本文标签: JavaScript regex to capture everything after the second to last backslashStack Overflow