JavaScript:在字符串中搜索字符串

时间:2009-07-29 12:40:12

标签: javascript regex

我需要找到一个能够解决我遇到的问题的正则表达式。

  

查询:barfly london

     

应匹配:Camden Barfly ,49 Chalk Farm Road,伦敦,NW1 8AN

我为此尝试了很多很多正则表达式,但到目前为止还没有任何工作。我正在考虑,也许我需要将搜索分成两个单独的查询才能生效。

有人能指出我正确的方向吗?我对这个领域有点新鲜。

5 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:2)

如果你想搜索两个字符串文字,我建议你不要使用正则表达式,而是使用正常的字符串搜索两次:

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

如果您不关心区分大小写,那么您可以相应地小写/大写测试字符串和字符串文字。

答案 2 :(得分: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 

答案 3 :(得分:0)

theString.match(new RegExp(query.replace('','\ b。* \ b'),'i'))

答案 4 :(得分: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");
}