说明
^(?:https?:\/\/)?[^\/]+\/|([^?\n]+)
![Regular expression visualization](https://www.debuggex.com/i/2uNiwPhBfhhw7L_2.png)
这个正则表达式将执行以下操作:
- 匹配字符串开始
http://
或https://
- 跳过域名
- 捕捉的子域名之后和查询字符串之前
例
现场演示
https://regex101.com/r/zC4gZ6/1
示例文本
youtube.com/data/beta
http://youtube.com/data/beta?Droid=This_is_not_the_droid_you_are_looking_for
样品匹配
[1][0] = youtube.com/data/beta
[1][1] = data/beta
[2][0] = http://youtube.com/data/beta
[2][1] = data/beta
说明
NODE EXPLANATION
----------------------------------------------------------------------
^ the beginning of a "line"
----------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
----------------------------------------------------------------------
http 'http'
----------------------------------------------------------------------
s? 's' (optional (matching the most amount
possible))
----------------------------------------------------------------------
: ':'
----------------------------------------------------------------------
\/ '/'
----------------------------------------------------------------------
\/ '/'
----------------------------------------------------------------------
)? end of grouping
----------------------------------------------------------------------
[^\/]+ any character except: '\/' (1 or more
times (matching the most amount possible))
----------------------------------------------------------------------
\/ '/'
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
[^?\n]+ any character except: '?', '\n'
(newline) (1 or more times (matching the
most amount possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
加分
要包括查询字符串,如果他们存在,那么添加(?:\?(.*?))?$
上述表达式的末尾,以便它看起来像这样。
^(?:https?:\/\/)?[^\/]+\/([^?\n]+)(?:\?(.*?))?$
![Regular expression visualization](https://www.debuggex.com/i/ZPNPqE5LAOo07yqV.png)
感谢滚装哟,你真棒。但我只有一个问题,我怎样才能将查询字符串也包含在结果中? –
我刚在我的答案的末尾提供了一个更新来覆盖查询字符串部分。这允许查询字符串部分存在或不存在。 –