【问题标题】:How to match all word which starts with a space and character如何匹配所有以空格和字符开头的单词
【发布时间】:2019-12-24 18:08:54
【问题描述】:

我无法突出显示以space 开头并以某个字符开头的word

这些字符在下面列出:

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

问题:突出显示整个word,如果它以space 开头并以find search key 开头。在完全匹配的情况下突出显示它们。

测试用例:

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

以下是我尝试过的:

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>

【问题讨论】:

  • 您会反对使用数组和字符串匹配而不是冗长的 RegEx 的解决方案吗?
  • 您是要匹配还是突出显示?正则表达式不是这项工作的工具。见How to highlight text using javascript

标签: javascript jquery regex


【解决方案1】:

由于您需要空格,因此您可以使用\s 使用lookbehind 查找空格,并使用\S* 查找列表项后面的非空格字符。

注意:并不普遍支持 Lookbehinds。最值得注意的是Firefox, Edge, and IE(由 MonkeyZeus 在comment 中添加)。

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(`((?<=(^|\\s))(?:${list.join('|')})\\S*)`, 'ig')
var textDescription = textDescription.replace(pattern, '<highlight>$&</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>

【讨论】:

【解决方案2】:

你需要:

  • 确保您的搜索文本是escaped to be used in regex
  • 确保匹配搜索文本后的其余非空白字符(为此使用\S*
  • 使用(\s|^) 左侧边界(或(?&lt;!\S),如果您仅针对ECMAScript 2018+ JS 环境)匹配空格或字符串开头(因为(?&lt;!\w) = (?&lt;=(^|\W)) 匹配任何不是前面有一个单词 char,即字母、数字或_)。

固定的代码如下所示

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>

所以,正则表达式看起来像

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

请参阅regex demo online详情

  • (\s|^) - 捕获组 1:空格或字符串开头
  • ((?:Alex|&amp;|2009|&gt;|ph)\S*) - 捕获组 2:
    • (?:Alex|&amp;|2009|&gt;|ph) - 匹配任一搜索短语的非捕获组
    • \S* - 除空格外的任何 0+ 个字符

替换为第 1 组值 ($1)、&lt;highlight&gt;、第 2 组值 ($2) 和 &lt;/highlight&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多