我找到了一个正则表达式 here .试试下面的字符串,我面临的问题是在第一个捕获组之后的每个捕获组的开头都有一个额外的空格。我需要空格被匹配但我不需要它们被捕获。
正则表达式:
^(\/[a-zA-Z0-9]+)?(\s~[a-zA-Z]+)?([\w\s'()-]+)?((?:\s~[a-zA-Z]+){0,2})?$
在上面的链接中查看它会更容易理解。
您可以将这些字符串一一粘贴到测试字符串区域:
/test ~example matches ~extra ~space
this too has an extra ~space ~matched
/like wise for this
/and ~this
查看匹配组区域,注意在第 1 个组之后,捕获了组之间的第一个空格。
我想做的是:
对于第一个和第二个捕获组,我希望它们检测一个后续空间并吸收但不捕获它,这样第三个捕获组不会检测和捕获额外的空间。对于第 4 个捕获组,我希望它检测前面的空格并吸收它但不捕获它。
我所说的 absorb 是指空间被“移除”,第三个捕获组不会意识到它的存在。
我该怎么做?
谢谢。
最佳答案
这是我想出的正则表达式-
^(\/[a-zA-Z0-9]+)?(?:\s)?(~[a-zA-Z]+)?(?:\s)?([\w\'()\-\s]+)?(?:\s(~[a-zA-Z]+))?(?:\s(~[a-zA-Z]+))?$
根据要求将正则表达式分为两部分-
For the 1st and 2nd capture group, I want them to detect a succeeding space and absorb it but not capture it, so that the 3rd capture group won't detect and capture the extra space.
第一组和第二组的正则表达式 -
(\/[a-zA-Z0-9]+)?(\s~[a-zA-Z]+)?
因此,在每个第一和第二捕获组之后,我添加了一个非捕获 (?:\s)? .这允许第三个捕获组不吸收前面的空间。这是我的正则表达式 -
(\/[a-zA-Z0-9]+)?(?:\s)?(~[a-zA-Z]+)?(?:\s)?
For the 4th capture group, I want it to detect a preceding space and absorb it but not capture it.
你的正则表达式
((?:\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"]
希望这对您有所帮助。
关于javascript - 如何在不捕获它的情况下在捕获组 "absorb"之前/之后制作空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594944/