2010-11-18 96 views
0

我在php中使用此代碼來檢測字符串中是否有五個相同的符號在一行中並執行一些代碼,如果它。正則表達式在javascript中搜索

function symbolsInRow($string, $limit = 5) { 
    $regex = '/(.)\1{'.($limit - 1).',}/us'; 
    return 0 == preg_match($regex, $string); 
} 

現在我需要在JavaScript中做同樣的事情,但不幸的是我不夠熟悉它。這個函數怎樣才能轉換成javascript?如果函數在給定的字符串中找到5個相同的符號,該函數應該返回false。

回答

1

在這裏你去,如果找到匹配

function symbolsInRow(string, limit) { 
    // set the parameter to 5 if it is not provided 
    limit = (limit || 5); 

    // create a regexp object, initialized with the regex you want. we escape the \ with \\ because it is a special char in javascript strings. 
    var regex = new RegExp('(.)\\1{'+(limit-1)+',}'); 

    // return false if we find a match (true if no match is found) 
    return !regex.test(string); 
} 

實際test方法將返回true。因此,請注意!這是not運算符對測試結果的反轉,因爲如果找到序列就想返回false。

例如在http://www.jsfiddle.net/gaby/aPTAb/

+0

爲什麼'g'修飾符? – 2010-11-18 15:07:55

+0

@Victor,以防萬一在字符串中有換行符。 – 2010-11-18 15:33:12

+1

換行符? 'g'與換行符無關。 – jwueller 2010-11-18 17:59:10

1

可以用正則表達式是不是:

function symbolsInRow(str, limit, symbol){ 
    return str.split(symbol).length === limit + 1; 
} 
+0

我寧願使用正則表達式,如果它是可能的,因爲我需要單獨執行每個符號的檢查做。字符串中的任何符號都不應該連續使用五次以上,但可以在不同位置使用任意數量的符號。例如,這個「somethiiiiiiiiing」應該返回false,但「somethininininining」不應該... – 2010-11-18 14:51:07

+1

原始問題要求任何**符號(也就是說,你不能指望調用者知道「符號」是什麼。 ..)在連續**中重複五次**(所以'aaa-aa'不會返回'true')。 – 2010-11-18 14:55:31

+0

在我的法語口語大腦中,從「連續」到「sur une ligne」的錯誤翻譯... – Mic 2010-11-18 15:05:28

1

這應該是等價的:連續

function symbolsInRow(string, limit) { 
    limit = (limit || 5) - 1; 
    return !(new RegExp('(.)\\1{'+limit+'}')).test(string); 
} 
+0

在Javascript正則表達式中,修飾符「u」是不必要的,'s'是默認值(必須使用' m'回到多線模式)。 – 2010-11-18 14:51:56

+0

@Victor Nicollet:那是對的。我已經修好了。 – jwueller 2010-11-18 14:52:36

+0

現在你需要把'\'變成'\\';) – 2010-11-18 14:56:43

0

五年,區分大小寫,這應該工作:

function symbolsInRow(string) { 
    return /(.)\1{4}/.test(string); 
} 

如果您需要匹配任意數量的重複:

function symbolsInRow(string,limit) { 
    return (new RegExp('(.)\\1{'+limit+'}')).test(string); 
}