Regexp - select everything before the 3rd slash

让人想犯罪 __ 提交于 2021-02-17 06:58:25

问题


What would be the easiest regexp selecting all before the 3rd slash

I tried this:

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

But it does not work exactly as I would hope it would do. Whats more i dont know that it will work in Google Analytics (Filter Section)


回答1:


What you might do instead is ot repeat matching 2 times not a forward slash and then a forward slash.

^(?:[^\/]*\/){2}[^\/]+

See a regex demo

If you don't want to match ?# you could add that to the character class

^(?:[^\/?#]*\/){2}[^\/]+

About your pattern

This part of your pattern ([^\/?#]+){3} captures in a group matching 1+ times any character that is not in the character class but after that repetition takes no forward slash into account.

Then (?:.*?\/) will match any character non greedy followed by a forward slash.




回答2:


In your comment, you give three examples: /, /news/ and /news/details/. Based on these examples, here is a solution:

^(\/[^\/]*){1,2}\/?

It says: from the start of the string match the following:

  • a slash, then zero or more non-slashes
  • optionally followed by a second slash plus zero or more non-slashes
  • optionally followed by a final slash



来源:https://stackoverflow.com/questions/56002107/regexp-select-everything-before-the-3rd-slash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!