我有以下文字:
快速的棕色狐狸跳过懒狗。美国联邦通信委员会必须审查网络,并说& $#* @!。有614个学生的实例达到90.0%或以上。
我希望找到文字:
&安培;!$#* @
我已定义以下RegEx来查找上述文本:
[^0-9a-zA-Z\s.]
它确实找到了上述文本中的匹配项,但我希望找到重复出现的内容。如果我只是多次键入它,它确实有效。像这样:
[^0-9a-zA-Z\s.][^0-9a-zA-Z\s.][^0-9a-zA-Z\s.][^0-9a-zA-Z\s.][^0-9a-zA-Z\s.][^0-9a-zA-Z\s.]
现在我放置一个星号表示零次或多次出现:
[^0-9a-zA-Z\s.]*
([^0-9a-zA-Z\s.])*
他们没有工作。但是,当我尝试这个时(使用/g
修饰符):
([^0-9a-zA-Z\s.]*)
我的结果是 155 。请看这个链接:https://regex101.com/r/yJ9dN7/2
如何修改上述代码才能匹配&$#*@!
?
答案 0 :(得分:2)
使用+
量词匹配1个或多个匹配项:
[^0-9a-zA-Z\s.]+
^
请参阅regex demo
或者,作为Sebastian Proske comments,为了使匹配更精确,您可以使用限制量词 {2,}
来匹配2个或更多,或{3,}
来匹配3个或更多等(见底部的备忘单)。
var re = /[^0-9a-zA-Z\s.]+/;
var str = 'The quick brown fox jumped over the lazy dog. The FCC had to censor the network for saying &$#*@!. There were 614 instances of students getting 90.0% or above.';
if (m=str.match(re)) {
console.log(m[0]);
}

JS Quantifier Cheat Sheet :
+ once or more
A+ One or more As, as many as possible (greedy), giving up characters if the engine needs to backtrack (docile)
A+? One or more As, as few as needed to allow the overall pattern to match (lazy)
* zero times or more
A* Zero or more As, as many as possible (greedy), giving up characters if the engine needs to backtrack (docile)
A*? Zero or more As, as few as needed to allow the overall pattern to match (lazy)
? zero times or once
A? Zero or one A, one if possible (greedy), giving up the character if the engine needs to backtrack (docile)
A?? Zero or one A, zero if that still allows the overall pattern to match (lazy)
{x,y} x times at least, y times at most
A{2,9} Two to nine As, as many as possible (greedy), giving up characters if the engine needs to backtrack (docile)
A{2,9}? Two to nine As, as few as needed to allow the overall pattern to match (lazy)
A{2,} Two or more As, greedy
A{2,}? Two or more As, lazy (non-greedy).
A{5} Exactly five As. Fixed repetition: neither greedy nor lazy.
答案 1 :(得分:0)
答案 2 :(得分:0)
var text = 'The quick brown fox jumped over the lazy dog. The FCC had to censor the network for saying &$#*@!. There were 614 instances of students getting 90.0% or above.';
console.log(text.match(/[^A-z0-9\s.]+/g, ''));
这种情况下的问题是" 90.0%"%,你想要这个角色吗?或者你可以排除它?