如何匹配所有以空格和字符开头的单词 [英] How to match all word which starts with a space and character

查看:94
本文介绍了如何匹配所有以空格和字符开头的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在突出显示以space开头并以某个字符开头的word时遇到问题.

i have problem with highlighting word which starts with space and begins with some character.

这些字符在下面列出:

var list = ['Alex','&','2009','>','ph'];//动态出现

问题:如果整个wordspace开头并以find search key开头,则突出显示整个word.如果完全匹配,请突出显示它们.

Question: highlight whole word if it starts with space and begins with find search key. in case of exact match highlight them.

测试案例:

 1. with `ph` `Philip's` should highlight.    not `.Philip's`
 2. with `>` `>20` should highlight.

以下是我尝试过的内容:

below is what i have tried:

var list = ['Alex','&','2009','>','ph']; // comes dynamically

var textDescription = `Alexander the Great (Ancient Greek: Ἀλέξανδρος ὁ Μέγας, romanized: Aléxandros ho Mégas), was a king (basileus) of the ancient Greek kingdom of Macedon[a] and a member of the Argead dynasty. He was born in Pella in 356 BC and succeeded his father Philip II to the throne at the age of 20. He spent most of his ruling years on an unprecedented military campaign through Asia and northeast Africa, and by the age of thirty, he had created one of the largest empires of the ancient world, stretching from Greece to northwestern India.[1][2] He was undefeated in battle and is widely considered one of history's most successful military commanders.[3]

During his youth, Alexander was tutored by Aristotle until age 16. After Philip's assassination in 336 BC, he succeeded his father to the throne and inherited a strong kingdom in 2009 BC & 2010 BC. Alexander is > 20090 people.  .>20 and >20.34&&() and 30> >`

var pattern = new RegExp(`(?<=(^|\\W))((\s\w*)${list.join('|')})(?=(\\W|$))`, 'ig')
var textDescription = textDescription.replace(pattern, '<highlight>$2</highlight>')

$('#highlight').html(textDescription)

highlight {
  color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="highlight"></div>

推荐答案

您需要:

  • 请确保您的搜索文本已转义为可在正则表达式中使用
  • 确保匹配搜索文本后其余的非空白字符(为此使用\S*)
  • 使用(\s|^)左边界(如果仅将ECMAScript 2018+ JS环境作为目标,则使用(?<!\S))以匹配空格或字符串开头(因为(?<!\w) = (?<=(^|\W))匹配任何不属于该位置的位置)前面有一个字符char,即字母,数字或_).
  • Make sure your search texts are escaped to be used in regex
  • Make sure the rest of the non-whitespace chars after the search texts are matched (use \S* for that)
  • Use (\s|^) left-hand boundary (or (?<!\S) if you are targeting ECMAScript 2018+ JS environments only) to match a whitespace or start of string (as (?<!\w) = (?<=(^|\W)) matches any location that is not preceded with a word char, i.e. letter, digit or _).

固定代码如下

var list = ['Alex','&','2009','>','ph'];

var textDescription = "Alexander the Great (Ancient Greek: Ἀλέξανδρος ὁ Μέγας, romanized: Aléxandros ho Mégas), was a king (basileus) of the ancient Greek kingdom of Macedon[a] and a member of the Argead dynasty. He was born in Pella in 356 BC and succeeded his father Philip II to the throne at the age of 20. He spent most of his ruling years on an unprecedented military campaign through Asia and northeast Africa, and by the age of thirty, he had created one of the largest empires of the ancient world, stretching from Greece to northwestern India.[1][2] He was undefeated in battle and is widely considered one of history's most successful military commanders.[3]\n\n    During his youth, Alexander was tutored by Aristotle until age 16. After Philip's assassination in 336 BC, he succeeded his father to the throne and inherited a strong kingdom in 2009 BC & 2010 BC. Alexander is > 20090 people.  .>20 and >20.34&&() and 30> >";

var pattern = new RegExp('(\\s|^)((?:' + list.map(function(x) {
    return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}).join('|') + ')\\S*)', 'ig');
console.log(pattern);
var textDescription = textDescription.replace(pattern, '$1<highlight>$2</highlight>')

$('#highlight').html(textDescription)

highlight {
  color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="highlight"></div>

因此,正则表达式看起来像

So, the regex will look like

/(\s|^)((?:Alex|&|2009|>|ph)\S*)/gi

请参见 regex在线演示. 详细信息:

  • (\s|^)-捕获组1:空格或字符串开头
  • ((?:Alex|&|2009|>|ph)\S*)-捕获组2:
    • (?:Alex|&|2009|>|ph)-与任何搜索词组匹配的非捕获组
    • \S*-除空格以外的任何0+个字符
    • (\s|^) - Capturing group 1: a whitespace or start of a string
    • ((?:Alex|&|2009|>|ph)\S*) - Capturing group 2:
      • (?:Alex|&|2009|>|ph) - a non-capturing group matching any one of the search phrases
      • \S* - any 0+ chars other than whitespace

      替换为组1值($1),<highlight>,组2值($2)和</highlight>.

      The replacement is Group 1 value ($1), <highlight>, Group 2 value ($2) and </highlight>.

      这篇关于如何匹配所有以空格和字符开头的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆