开发者

regex for searchterm

I need help in constructing RegEx for the search function on my website. I am currently using JQuery framework. The goal is to go through paragraphs in XML and returns node that contains keywords inserted in the search text field.

For example, user may enter "Lorem Sed Pellentesque" in the search text field and I would like to use the keywords enter in the text field and go through the paragraph and find these keywords no matter the position of the keywords. Below is the sample of the paragraph:

Nullam accumsan leo ultrices nisi consectetur blandit. Integer aliquam, urna nec vestibulum posuere, est ante sollicitudin tortor, non feugiat eros orci vitae dui. In lacus nulla, feugiat vitae porta vel, lobortis eget ligula. Sed e开发者_JAVA技巧gestas aliquet orci ut varius. Pellentesque ullamcorper magna eu sem convallis elementum.

So in this case, this paragraph will be considered as one of the results since it contains "Sed" and "Pellentesque" keywords.

Is it possible to construct RegEx that can go through the whole paragraph? It does not matter if it is case-sensitive or not.

Any help is really appreciated! Thank you in advance.


Something like this (not very robust but will work for alphanumeric keywords):

var keywords = $('input').text().replace(" ", "|");
var re = new RegExp(keywords, "gi"); // make it global, case insensitive
var matches = re.exec("paraText");

Although, you can do it without regex:

var keywords = $('input').text().split();
$(keywords).each(function() {
  if(paraText.indexOf(this) > 0) {
    // keyword found
  }
});

If you want to match between word boundaries, you need some regex like this:

var keywords = $('input').text().split();
$(keywords).each(function() {
  var re = new RegExp("\\b" + this + "\\b");
  if(re.test(paraText)) {
    // keyword found
  }
});


    <script>
    var a=text.replace(/(Nullam|ligula|in)/ig,'<b>$1</b>');
    $('#ttt').html(a);
    </script>
<div id='ttt'>Nullam accumsan leo ultrices nisi consectetur blandit. Integer aliquam, urna nec vestibulum posuere, est ante sollicitudin tortor, non feugiat eros orci vitae dui. In lacus nulla, feugiat vitae porta vel, lobortis eget ligula. Sed egestas aliquet orci ut varius. Pellentesque ullamcorper magna eu sem convallis elementum.</div>

sample there: http://jsfiddle.net/oceog/q8S7E/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜