var str = ")shenmajs-(shenmajsb)hghghg";
var reg = /\b[^aoieu][a-z]*\b/g;
str.match(reg);
//returns ["shenmajs", "shenmajsb", ")hghghg"]
我想匹配不以字母[aoieu]开头的单词。返回数组的第一项是“shenmajs”,但第三项是“)hghghg”。我不明白为什么“)”可以包含该项目。你能帮助我吗?谢谢
最佳答案
以下是您在 regexr 上的案例的在线 View :http://gskinner.com/RegExr/?325rr
包含")"是因为正则表达式 [^aeiou]
表示除 a、e、i、o 或 u 之外的任何字符。其中包括“)”。
正则表达式的工作方式与 anchor \b
的解释方式有关。来自 this page
There are three different positions that qualify as word boundaries:
Before the first character in the string, if the first character is a wor d character.
After the last character in the string, if the last character is a word character.
Between two characters in the string, where one is a word character and the other is not a word character.
所以你的第一个 \b
在第一个 s 之前匹配,不是在最初的“)”之前(因为你没有根据规则 1 获得初始单词边界) 。第一场比赛以破折号之前的 anchor 结束。下一场比赛将从“(”和 s 之间的 anchor 开始,因为您无法从破折号开始匹配!(尝试一下!)。您的第三场比赛现在将从 b 和 "之间的 anchor 开始)”。由于“)”不在 [aeiou]
中,因此可以开始下一场比赛。而且它的效果也很好:它后面紧跟着零个或多个带有结尾词边界的 a-z!
关于javascript - 我想匹配不以字母 [aoieu] 开头的单词,但正则表达式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12452771/