我无法弄清楚可以匹配以下示例的正则表达式:
我需要捕获/之间的每个变量。
示例:/ abc / efg / xxx应返回:
笔记:
我没有找到比这个更清洁的方法来解决你的问题,正如你所说:
^\/(?:(\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 /也适用,不应该。如果你能忍受这个,你应该没问题。
希望这可以帮助。