正则表达式语法匹配/,/ abc /,/ abc / efg /等的任何组合

问题描述 投票:-2回答:1

我无法弄清楚可以匹配以下示例的正则表达式:

  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
1个回答
1
投票

我没有找到比这个更清洁的方法来解决你的问题,正如你所说:

^\/(?:(\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 /也适用,不应该。如果你能忍受这个,你应该没问题。

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.