在/之前或之间或之后捕获最后一个元素?

Capture last element either between or after / and before?

假设我有以下网址:

https://test.com/welcome/
https://sub.test.com/home/edit
https://test.com/home/view?view=column
https://test.com/home/view/?view=list

我想捕获以下结果:

welcome
edit
view
view

现在我有 (?:\/[^\/]+)+?\/(.*?)/{0,1}$(?:\/[^\/]+)+?(?:.*\/)(.*?)\?{0,1}$(?:\/[^\/]+)+?(?:.*\/)(.*)/\?.*$,但它们很复杂,我似乎无法将它们组合起来。

在 Splunk 中,您可以使用正则表达式来匹配所有文本,直到最后一次出现 / 后跟除 /? 或 [=14 之外的任何 1+ 个字符=] 并且可以使用命名捕获组捕获这 1+ 个字符:

".*/(?<lasturlpart>[^/?#]+)"

请参阅演示中使用的 regex demo. Note the \n or (?:/?(?:[#?].*|$)) in 以确保匹配不会跨行溢出,因为在演示中输入是单个多行字符串,而您将对独立字符串使用正则表达式。

图案详情

  • .* - 除换行字符外的任何 0 个或更多字符,尽可能多
  • / - 一个 / 字符
  • (?<lasturlpart>[^/?#]+) - 命名的捕获组匹配除 /?#.
  • 以外的 1 个或多个字符

您可以使用普通正则表达式:

(?<=[\/])[^\/?=]+(?=\/?$|\/?\?)

Demo

正则表达式可以自由间距模式1编写,使其自记录:

/ 
(?<=[\/])     # match '/' or '?' in positive lookbehind
[^\/?=]+       # match 1+ chars other than '/', '?' and '='
(?=            # begin a positive lookahead
  \/?$         # optionally map '/' then match end of line    
  |            # or
  \/?\?        # optionally match '/' then match '?'
)              # end positive lookahead
/x             # free-spacing mode

1.我不知道 Splunk 是否支持自由间距模式,但这无关紧要,因为我使用它只是为了展示正则表达式的工作原理。

| makeresults
| eval _raw="https://test.com/welcome/
https://sub.test.com/home/edit
https://test.com/home/view?view=column
https://test.com/home/view/?view=list"
| makemv delim="
" _raw
| stats count by _raw
| rex "^.*\/(?<result>\w+)"

贪心匹配就好

\w[a-zA-Z0-9_]