views:

237

answers:

5

I need to find a regular expression that would be able to work around an issue I am having.

Query: barfly london

Should match: Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN

I've tried many, many regex's for this, but none have worked so far. I am considering that maybe I will need to split the search into two separate queries for it to work.

Could anyone point me in the right direction? I'm a bit new to this area.

+3  A: 

Try this:

var r = /barfly|london/gi
str = "Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN"
alert(str.match(r).length>1)
mwilcox
`|` matches any, not all.
Crescent Fresh
this is pretty darn close to what I need, the only problem is it must match *all* not any
tombazza
I stand by my solution because the final test of the length is to ensure there are at least two matches. It would only fail in edge cases, like living on Barflybarfly road in Manchester.
mwilcox
+2  A: 

I'd suggest not using regexs if you want to search for two string literals, and instead use normal string searching twice:

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

If you're not concerned about case-sensitivity, then you can just lowercase/uppercase your test string and your string literals accordingly.

Dominic Rodger
A: 

Check this:

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
Makram Saleh
A: 

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

palindrom
A: 

Dominic's solution without case sensitivity. This is what I needed for my project.

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");
}
kuester2000