Jack Guo
Jack Guo

Reputation: 23

Regular Expression to match two similar word

I run into a problem where the regular expression won't match two similar words:

Example:

bitcoin and bitcoin atm

Regular Expression:

new RegExp("(?:^|\\b)(bitcoin|bitcoin atm|test bitcoin)(?!\\w)");

Here's a demo :

(function myFunction() {

    var str = "bitcoin and bitcoin atm and test and test a and new test";
    
    var patt = new RegExp("(?:^|\\b)(bitcoin|bitcoin atm|test|test a|new test)(?!\\w)", "g");
    
    var res = str.match(patt);
    
    document.getElementById("demo").innerHTML = res;
    
})()
p{
  font-size: 30px;
}
<p id="demo"></p>

Upvotes: 2

Views: 78

Answers (1)

Ryan Tuosto
Ryan Tuosto

Reputation: 1951

Move more specific matches to be higher priority in your matching pattern.

(function myFunction() {

    var str = "bitcoin and bitcoin atm and test and test a and new test";

    var patterns = ['bitcoin', 'bitcoin atm','test', 'test a', 'new text'];

    patterns.sort(function(a,b){return b.length - a.length})
    
    var patt = new RegExp("(?:^|\\b)(" + patterns.join('|') + ")(?!\\w)", "g");
    
    var res = str.match(patt);
    
    document.getElementById("demo").innerHTML = res;
    
})()
p{
  font-size: 30px;
}
<p id="demo"></p>

Upvotes: 3

Related Questions