在比赛之前和之后查找文本-jQuery

问题描述:

我正在尝试进行搜索,并返回包含搜索项的代码段.

I am trying to do a search and return the snippet that contains the search term.

输入:`我是一名飞行员.我也可以弹钢琴,但是他不是

Input: `I am a pilot. I can also play piano, however he am not a

好歌手.

我会做意大利菜.

搜索:钢琴

结果:也弹钢琴,但是我不是

Result: also play piano, however I am not

规则:

  • 搜索词前两个词+搜索词+搜索词后四个词.
  • 不区分大小写.
  • 完全匹配,并且如果搜索词是单词的一部分,则应忽略.搜索 man 时应忽略 Cayman Island .

var needle = "Piano";
var haystack = "I am a pilot. I can also play piano, however I am not a 

good singer.
I cook Italian."; // the user input from a textarea would fill in this variable and would contain new line character

search_regexp = new RegExp('/([^'+ needle +']+)'+ needle +'([^'+ needle +']+)/', "gi");
thismatcharray = haystack.match(search_regexp);
alert(thismatcharray); 

我很想了解如何获取搜索值之前和之后的值组成的数组,以便可以串联以获得最终结果.谢谢....

I am keen to understand how can I get an array with the values before and after the search value so that I can concatenate to get the final result. Thanks....

尝试此正则表达式.它会寻找1到2个单词组([A-Za-z]+),然后是可选的标点符号(我允许使用.,,您可以根据需要扩展该组)和一些空格,然后是针号,然后是1到4组可选的标点符号,一些空格和一个单词.由于量词是贪婪的,因此如果前面有两个单词,后面有四个单词,那么它们将返回.

Try this regex. It looks for 1 to 2 groups of a word ([A-Za-z]+) followed by optional punctuation (I've allowed for . and ,, you could expand that group as required) and some whitespace, followed by the needle, followed by 1 to 4 groups of optional punctuation, some whitespace and a word. Since the quantifiers are greedy, if there are two words before and four after, that is what they will return.

var needle = "Piano";
var haystack = "I am a pilot. I can also play\n\
\
piano, however I\n\
am not a\n\
good singer.";
search_regexp = new RegExp('((([A-Za-z]+[.,]?\\s+){1,2})('+needle+')(([.,]?\\s+[A-Za-z]+){1,4}))', "gi");
var thismatcharray = haystack.match(search_regexp);
console.log(thismatcharray);
replace_regexp = new RegExp('^[\\s\\S]*?((([A-Za-z]+[.,]?\\s+){0,2})(\\b'+needle+'\\b)(([.,]?\\s+[A-Za-z]+){0,4}))[\\s\\S]*$', "i");
var output = haystack.replace(replace_regexp, '$2<label style="color: red">$4</label>$5');
console.log(output);