正则表达式匹配两个相似的单词

时间:2017-04-07 17:47:26

标签: javascript regex

我遇到一个问题,正则表达式与两个相似的单词不匹配:

实施例

bitcoin and bitcoin atm

正则表达式:

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

这是一个演示:

(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>

1 个答案:

答案 0 :(得分:3)

将更具体的匹配移动到匹配模式中的优先级更高。

&#13;
&#13;
(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;
    
})()
&#13;
p{
  font-size: 30px;
}
&#13;
<p id="demo"></p>
&#13;
&#13;
&#13;