首页 > 解决方案 > 匹配 /、/abc/、/abc/efg/ 等的任何组合的正则表达式语法

问题描述

我想不出可以匹配以下示例的正则表达式:

  1. /
  2. /abc
  3. /abc/
  4. /abc/xxx
  5. /abc/efg/
  6. /abc/efg/xxx

我需要捕获 / 之间的每个变量。

示例:/abc/efg/xxx 应该返回:

  1. 变量 1:abc
  2. 变量 2:efg
  3. 变量 3:xxx

笔记:

  1. / 之间的文本将始终是字母数字
  2. 以上 6 个用例是我唯一关心的情况。

标签: regex

解决方案


我没有找到比这个更干净的方法来完全按照您所说的那样解决您的问题:

^\/(?:(\w+)(?:\/(\w+)(?:\/(\w+))?)?)?((?<!\/)\/)?$

你可以在这里查看:https ://regex101.com/r/FJuJ43/6

解释 :

starts with a /: ^\/    
rest of unstored group is optional: (?: … )?    
may ends with a / unless there is another one just before: ((?<!\/)\/)?$
in the main group, first stored alphanum only subgroup: (\w+)
followed by another optional unstored subgroup, starting with a / and followed by another alphanum only stored subgroup: (?:\/(\w+) … )?
and ditto: (?:\/(\w+))?

这有效,创建了三个组。

但我不能阻止最后一个字符是尾随 /

/aaa/bbb/ccc/ 在不应该的时候也可以工作。如果你能忍受这一点,你应该没问题。

希望这可以帮助。


推荐阅读