javascript - 我想匹配不以字母 [aoieu] 开头的单词,但正则表达式不起作用

标签 javascript regex

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:

  1. Before the first character in the string, if the first character is a wor d character.

  2. After the last character in the string, if the last character is a word character.

  3. 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/

相关文章:

javascript - 每小时时间范围内累计记录数

javascript - Angular - 更新 $scope 后无法正确加载 div

javascript - 使用高效算法对数组中的相同对进行计数

javascript - 以任何顺序匹配查询中所有单词的正则表达式

php - 使用 preg_match 在 PHP 中解析 A​​pache 日志

python - 将两个正则表达式连接在一起

javascript - 如何将组件定位在我所有 QML View 的顶部

data-structures - 用于列表(数据结构)可视化的 Javascript 库

ios - 将NSRegularExpression更新为特定模式

regex - 组件 Tperlregex fatal error L3169?