2016-08-11 36 views
2

我有以下文字:正則表達式方括號中有星號的

敏捷的棕色狐狸跳過了懶狗。美國聯邦通信委員會不得不審查網絡說& $#* @ !.共有614名學生獲得90.0%或以上的成績。

,我想查找的文字:

& $#* @!

我已經定義了以下正則表達式查找上面的文字:

[^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.]*) 

我收到約結果。請參閱此鏈接:https://regex101.com/r/yJ9dN7/2

如何修改上述代碼以便匹配&$#*@!

回答

1

使用+量詞來匹配1個或多個:

[^0-9a-zA-Z\s.]+ 
      ^

regex demo

或者,作爲Sebastian Proske comments,使匹配更精確,你可以使用限制量詞{2,}到匹配2或更多,或{3,}以匹配3個或更多,等等(參見底部的cheatsheet)。

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]); 
 
}

Quantifier Basics

JS量詞小抄

+   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. 
+0

我寧願用'{2,}'代替'+',因爲如果它在'&##* @!' –

+0

之前,你也會匹配'%'-90.0% @SebastianProske:選擇取決於OP,我添加了一個完整的量詞cheatsheet。 –

0

如果你想只得到& $#* @!然後使用這個正則表達式,

regex=(&\$#\*@!) 

你可以看到結果在下面的link

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%」的%,你想要這個字符嗎?或者你可以排除它?