我遇到一个问题,正则表达式与两个相似的单词不匹配:
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>
答案 0 :(得分:3)
将更具体的匹配移动到匹配模式中的优先级更高。
(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;