使用 RegEx 提取 URI 或路径的最后路径段

Extract the last path-segments of a URI or path using RegEx

我正在尝试提取以下字符串的最后一部分:

"/subscriptions/5522233222-d762-666e-555a-e6666666666/resourcegroups/rg-sql-Belguim-01/providers/Microsoft.Compute/snapshots/vm-sql-image-v3.3-pre-sysprep-Oct-2021-BG"

我要捕捉:

"snapshots/vm-sql-image-v3.3-pre-sysprep-Oct-2021-BG"

我尝试了以下但没有成功:

(\w*?\/\w*?)$

如何使用正则表达式解决这个问题?

使用

[^\/]+\/[^\/]+$

参见regex proof

解释

--------------------------------------------------------------------------------
  [^\/]+                   any character except: '\/' (1 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  \/                       '/'
--------------------------------------------------------------------------------
  [^\/]+                   any character except: '\/' (1 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

您的问题

(\w*?/\w*?)$ 用于简单或空的最后 2 段 (tested),例如

  1. 匹配hello/world/subscriptions123/snap_shots捕获subscriptions123/snap_shots
  2. 匹配 /1/2// 捕获最后 2 个空段

好的是:

  • capture-group
  • / 匹配结束前的最后一个 path-separator ($)
  • \w*?意在匹配任意长度的path-segment

需要改进的地方:

  • *? 有点太不受限制了,选择量词 + 表示至少一个(而不是 * 表示任何或 ? 表示零或一个)
  • \w 适用于 word-meta-character,不匹配连字符或点(适用于 snapshot,不适用于给定的最后一段)

Quick-fixed

(\w+/[\w\.-]+)$ (tested)

  • 向包含 \w
  • 的 character-set 添加了点 \. 和连字符 -

简单而扎实

(snapshots/[^\/]+)$ (tested)

  • fore-last path-segment 假定为固定常数 snapshots
  • [^\/] 最后一段中除 (^) 斜杠外的任何字符

注意:斜杠不需要像

那样转义 \/