简体   繁体   English

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

[英]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> 

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM