2009-07-29 81 views
2

我需要找到一個能夠解決我遇到的問題的正則表達式。JavaScript:搜索字符串中的字符串

查詢:酒鬼倫敦

應符合:卡姆登酒鬼,49喬克農場路,倫敦,NW1 8AN

我試過很多,很多的正則表達式的這一點,但目前還沒有工作。我正在考慮,也許我需要將搜索分成兩個單獨的查詢來運作。

任何人都可以指向正確的方向嗎?我在這方面有點新鮮。

+1

非正則表達式的答案是否足夠? – 2009-07-29 12:51:46

+0

查詢中單詞的順序是否保留在主題字符串中? – palindrom 2009-07-29 13:35:35

回答

3

試試這個:

var r = /barfly|london/gi 
str = "Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN" 
alert(str.match(r).length>1) 
2

我建議不使用regexs如果你要搜索的兩個字符串值,而是使用普通的字符串搜索兩次:

var test="Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN" 
if ((test.indexOf("Barfly") != -1) && (test.indexOf("London") != -1)) { 
    alert("Matched!"); 
} 

如果你不關心區分大小寫,那麼你可以小寫/大寫你的測試字符串和相應的字符串文字。

1

檢查:

var my_text = "Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN, london again for testing" 
var search_words = "barfly london"; 

String.prototype.highlight = function(words_str) 
{ 
    var words = words_str.split(" "); 
    var indicies = []; 
    var last_index = -1; 
    for(var i=0; i<words.length; i++){ 
     last_index = this.toLowerCase().indexOf(words[i], last_index); 
     while(last_index != -1){ 
      indicies.push([last_index, words[i].length]); 
      last_index = this.toLowerCase().indexOf(words[i], last_index+1); 
     } 

    } 
    var hstr = ""; 
    hstr += this.substr(0, indicies[0][0]); 
    for(var i=0; i<indicies.length; i++){ 
     hstr += "<b>"+this.substr(indicies[i][0], indicies[i][1])+"</b>"; 
     if(i < indicies.length-1) { 
      hstr += this.substring(indicies[i][0] + indicies[i][1], indicies[i+1][0]); 
     } 
    } 
    hstr += this.substr(indicies[indicies.length-1][0]+indicies[indicies.length-1][1], this.length); 
    return hstr; 
} 

alert(my_text.highlight(search_words)); 
// outputs: Camden <b>Barfly</b>, 49 Chalk Farm Road, <b>London</b>, NW1 8AN, <b>london</b> again for testing 
0

theString.match(新的RegExp(query.replace( '', '\ B * \ B'), '我')。)

0

Dominic的解決方案,而區分大小寫。這是我爲我的項目所需要的。

var test="Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN"; 
if ((test.toLowerCase().indexOf("barfly") != -1) && (test.toLowerCase().indexOf("london") != -1)) { 
    alert("Matched"); 
} 
else { 
    alert("Not matched"); 
}