2013-01-11 50 views
1

我需要編寫一個正則表達式來使用JS .match()函數。目標是檢查一個字符串有多個選擇。例如,如果mystr包含word1或word2或word3,我想在下面的代碼中返回true多個選項的正則表達式

mystr1 = "this_is_my_test string_containing_word2_where_i_will_perform_search"; 
mystr2 = "this_is_my_test string_where_i_will_perform_search"; 
myregex = xxxxxx; // I want help regarding this line so that 
if(mystr1.match(myregex)) return true; //should return true 
if(mystr2.match(myregex)) return true; //should NOT return true 

請幫忙嗎?

+0

正則表達式會檢查str是否包含任何選項:word1,word2或word3? – Diego

+0

是的,這是我的意圖......但所有的單詞都會以逗號分隔格式的字符串。 – abdfahim

回答

3

所以使用OR |在您的正則表達式:

myregex = /word1|word2|word3/; 
+0

所以,如果我的話是在一個變量(逗號分隔),這個工作嗎? s = $ var.replace(「,」,「|」); myregex = new RegExp(s,「i」); – abdfahim

+0

@AbdullahFahim是的,應該工作。 –

0

的正則表達式是:/word1|word2|word3/

要知道,還有你的代碼會工作,你實際上是不使用你所需要的方法。

  • string.match(regex) - >返回匹配數組。當作爲布爾值計算時,它將在空時返回false(這就是它的工作原理)。
  • regex.test(string) - >是你應該使用的。它評估字符串是否與正則表達式匹配並返回truefalse
+0

謝謝..幫助 – abdfahim

0

如果您沒有使用您的匹配,那麼我可能傾向於使用test()方法幷包括i標誌。

if(/word1|word2|word3/i.test(mystr1)) return true; //should return true 
if(/word1|word2|word3/i.test(mystr2)) return true; //should NOT return true 
+0

感謝您的提示.. – abdfahim