Match everything in a string after the 3rd '/&

2019-10-07 22:42发布

I have two different forms of a string:

https://anexample.com/things/stuff

and

https:///things/stuff

I need a regular expression that will match everything in the string after the 3rd slash, no matter the syntax. Once it hits the 3rd slash, the rest of the string is matched. I have found a bunch of examples, but I can't seem to tweak the right way to get it to work. Thanks in advance.

标签: regex match
4条回答
时光不老,我们不散
2楼-- · 2019-10-07 23:16

You can use this regex:

^(?:[^\/]*\/){3}(.*)$

And use matched group #1

In javascript:

var s = 'https:///things/stuff';
m = s.match(/^(?:[^\/]*\/){3}(.*)$/);
// m[1] => things/stuff
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-10-07 23:23

Something like this should work, however I'm writting it without any testing, but it should look for three sections of any character any number of times followed by slash and then catch last section which is everything until line end - you can of course change delimiter to whitespace or whatever.

^.*/{3}(.*$)
查看更多
相关推荐>>
4楼-- · 2019-10-07 23:27

You can use this

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

Regular expression visualization

查看更多
爷、活的狠高调
5楼-- · 2019-10-07 23:31

Assuming PCRE, and that you won't have newlines in your string:

If the 3 slashes can be at any position (like your first example):

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

This could also be expressed as

^(:?[^/]*/){3}(.*)$

Using positive lookbehind, you could use the following, which should only match what you want instead of putting it into a capturing group:

(?<=^(:?[^/]*/){3}).*$

Any needed escaping due to used delimiters is left as an exercise to the reader of course ( if you use / as a delimiter, you have to escape all / in the expression, like \/)

And there's probably a million other alternatives, depending on what exact needs you have besides the ones you mentioned.

查看更多
登录 后发表回答