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

编程入门 行业动态 更新时间:2024-10-24 21:25:14
本文介绍了在比赛之前和之后查找文本-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);

更多推荐

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

本文发布于:2023-10-26 11:55:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530060.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!