我需要找到一个能够解决我遇到的问题的正则表达式。JavaScript:搜索字符串中的字符串
查询:酒鬼伦敦
应符合:卡姆登酒鬼,49乔克农场路,伦敦,NW1 8AN
我试过很多,很多的正则表达式的这一点,但目前还没有工作。我正在考虑,也许我需要将搜索分成两个单独的查询来运作。
任何人都可以指向正确的方向吗?我在这方面有点新鲜。
我需要找到一个能够解决我遇到的问题的正则表达式。JavaScript:搜索字符串中的字符串
查询:酒鬼伦敦
应符合:卡姆登酒鬼,49乔克农场路,伦敦,NW1 8AN
我试过很多,很多的正则表达式的这一点,但目前还没有工作。我正在考虑,也许我需要将搜索分成两个单独的查询来运作。
任何人都可以指向正确的方向吗?我在这方面有点新鲜。
试试这个:
var r = /barfly|london/gi
str = "Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN"
alert(str.match(r).length>1)
我建议不使用regexs如果你要搜索的两个字符串值,而是使用普通的字符串搜索两次:
var test="Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN"
if ((test.indexOf("Barfly") != -1) && (test.indexOf("London") != -1)) {
alert("Matched!");
}
如果你不关心区分大小写,那么你可以小写/大写你的测试字符串和相应的字符串文字。
检查:
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
theString.match(新的RegExp(query.replace( '', '\ B * \ B'), '我')。)
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");
}
非正则表达式的答案是否足够? – 2009-07-29 12:51:46
查询中单词的顺序是否保留在主题字符串中? – palindrom 2009-07-29 13:35:35