当特殊字符和数字介于两者之间时,使用javascript进行模式匹配不会起作用 [英] pattern matchin using javascript doesnt wrk when special characters and numbers come in between
问题描述
我正在尝试创建一种模式匹配以在我的网站的文章中查找单词内容.当单词之间有特殊字符或数字时,我无法进行模式匹配,因此我将添加jsfiddle链接..也有可能找到发生的次数并添加一个按钮,单击该按钮可以逐个地转到每个发生的事件...这就是我的pgrm当前正在运行的方式
I am trying to create a pattern matching to find word contents in an article for my website.. I am unable to make the pattern matchings when a special character or a number comes in between the words, I will add the jsfiddle link.. also is it possible to find the number of occurences and add a button which on clicking go to each occurence one by one...This is the way my pgrm is currently wrking http://jsfiddle.net/ehzPQ/12/
推荐答案
我认为问题与您为单词选择的边界有关,我相信\ b不会考虑单词的情况之前有一个点(例如".cancer9".但是我确实不是正则表达式方面的专家...所以,我做了一些工作并获得了此解决方案,但是我不确定它是否对您有用:
I think the problem has to do with the boundaries you choose for your words, I believe that with \b you are not taking into account the case where the word is has a dot before (like ".cancer9". But I'm really not an expert in regex... so, I worked a little bit and got this solution, but I'm not sure if it will work for you:
JavaScript:
Javascript:
$(document).ready(function () {
var $test = $('#article');
var entityText = $('#entity').html().replace(/\./g, "\\\.").replace(/\$/g, "\\\$").replace(/\?/g, "\\\?"); //etc...
var entityRegularExpression =new RegExp("([^a-zA-Z0-9])(" + entityText + ")([^a-zA-Z0-9])", "gi");
var highlight = '$1<span class="highlight">$2</span>$3';
$test.html($test.html().replace(entityRegularExpression, highlight));
});
这里有一个有效的演示: http://jsfiddle.net/ehzPQ/20/
And here you have a working demo: http://jsfiddle.net/ehzPQ/20/
让我知道它是否对您有用.
Let me know if it works for you.
这篇关于当特殊字符和数字介于两者之间时,使用javascript进行模式匹配不会起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!