regex - 匹配 /、/abc/、/abc/efg/ 等的任何组合的正则表达式语法
问题描述
我想不出可以匹配以下示例的正则表达式:
- /
- /abc
- /abc/
- /abc/xxx
- /abc/efg/
- /abc/efg/xxx
我需要捕获 / 之间的每个变量。
示例:/abc/efg/xxx 应该返回:
- 变量 1:abc
- 变量 2:efg
- 变量 3:xxx
笔记:
- / 之间的文本将始终是字母数字
- 以上 6 个用例是我唯一关心的情况。
解决方案
我没有找到比这个更干净的方法来完全按照您所说的那样解决您的问题:
^\/(?:(\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/ 在不应该的时候也可以工作。如果你能忍受这一点,你应该没问题。
希望这可以帮助。
推荐阅读
- javascript - ramda/函数式编程 - 基于条件的不同逻辑
- html - 如何摆脱 HTML 中的空白区域
- javascript - 将 Google 日历议程视图制作成卡片
- c - 我应该如何在 C 中实现点和向量?
- javascript - 如果测验在时间结束之前结束,我如何停止计时器功能?Javascript
- ubuntu-18.04 - sqoop 在我的 ubuntu 18.04 和 hadoop 3.1.3 上不起作用
- javascript - 使用 Ajax 创建博客罐后,我无法进行任何其他 Ajax 调用,并且 JsonResponse 返回空字符串
- javascript - 当对象实现接口时访问对象键?
- javascript - 无法在 Chrome 开发者工具中编辑脚本
- javascript - 悬停图像时播放 Youtube 视频