这是我想出的正则表达式-
^(\/[a-zA-Z0-9]+)?(?:\s)?(~[a-zA-Z]+)?(?:\s)?([\w\'()\-\s]+)?(?:\s(~[a-zA-Z]+))?(?:\s(~[a-zA-Z]+))?$
根据要求将正则表达式分为两部分-
对于第一个和第二个捕获组,我希望他们检测到一个成功的
空间并吸收但不捕获它,以便第三个捕获组
不会检测和捕获额外的空间。
第一组和第二组的正则表达式 -
(\/[a-zA-Z0-9]+)?(\s~[a-zA-Z]+)?
所以,在每个第一个和第二个捕获组之后,我添加了一个非捕获 (?:\s)? .这允许第三个捕获组不吸收前面的空间。这是我的正则表达式 -
(\/[a-zA-Z0-9]+)?(?:\s)?(~[a-zA-Z]+)?(?:\s)?
对于第 4 个捕获组,我希望它检测到前面的空格并
吸收它而不是捕获它。
你的正则表达式
((?:\s~[a-zA-Z]+){0,2})?
在这里,一个明显的解决方案是仅捕获文本部分([a-zA-Z])而不捕获 \s 部分。
像这样的,
(?:(?:\s(~[a-zA-Z]+)){0,2})?
^^^^^^^^^^ Capturing only this.
但这是一个重复的捕获组,您实际上是在旧元素之上捕获一个新元素。基本上,重复捕获组只会捕获最后一次迭代。
所以如果你想匹配-
" ~space ~matched",它只会捕获最后一个"~matched"。
因此,一种解决方案是,由于您正在检查它的 {0,2},您可以显式检查它 2 次,就像这样 -
(?:\s(~[a-zA-Z]+))?(?:\s(~[a-zA-Z]+))?
但是如果以后对 {0,2} 的要求发生变化,最好的解决方案是捕获前面的空格,然后将捕获的组按空格分开。
-> OUTPUT - when I run this regex for the given strings in JavaScript-
["/test ~example matches ~extra ~space", "/test", "~example", "matches", "~extra", "~space", index: 0, input: "/test ~example matches ~extra ~space"] (index):18
["this too has an extra ~space ~matched", undefined, undefined, "this too has an extra", "~space", "~matched", index: 0, input: "this too has an extra ~space ~matched"] (index):18
["/like wise for this", "/like", undefined, "wise for this", undefined, undefined, index: 0, input: "/like wise for this"] (index):18
["/and ~this", "/and", "~this", undefined, undefined, undefined, index: 0, input: "/and ~this"]
希望这会有所帮助。