使用动态RegExp获取$ 1捕获组 [英] Get $1 capture group with dynamic RegExp

查看:94
本文介绍了使用动态RegExp获取$ 1捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人知道我在这里做错了什么,我很好奇。我想在表达式中使用变量,但出于某些原因,当我尝试时,它似乎没有使用 $ 1 获取搜索词。

I was curious if anyone knows what I'm doing wrong here. I want to use a variable inside the expression but for some reason when I try to, it doesn't seem to grab the search term with the $1.

这回复正确:

$('.content').html(function(_,i) {
  return  i.replace(/(cat)/gi, '<span class="highlight">$1</span>');
});

出于某种原因,这不是:

For some reason, this does not:

$('.content').html(function(_,i) {
  var customVariable = 'cat';
  var pattern = new RegExp(customVariable,'gi');
  return  i.replace(pattern, '<span class="highlight">$1</span>');
});

我很高兴在RegExp中捕获群组,我找不到其他人遇到此问题所以我想我错过了一些非常简单的东西。

I'm very new to capture groups in RegExp and I couldn't find anyone else having this issue so I assume I'm missing something very simple.

推荐答案

你忘了括号:

var pattern = new RegExp('(' + customVariable + ')','gi');

$ 1 是对第1组的反向引用你没有。

$1 is a backreference to group 1 and you do not have any.

实际上,你可以找到更多关于JavaScript中的反向引用 替换在MDN网站上。确实,如果您不想在备选方案之前或之后匹配任何文本,您只需要设置一个捕获组,因为在使用正则表达式时,可以使用<$ c $引用整个匹配的文本。 c> $& 模式(在您的情况下,您只需要用 $& $ 1 c $ c>)。

Actually, you can find more about backreferences in JavaScript replace on MDN Web site. It is true that in case you do not want to match any text before or after the alternatives, you just do not need to set up a capturing group, since when using a regex the whole matched text can be referenced with a $& pattern (in your case, you just need to replace $1 with $&).


$&       插入匹配的子字符串。

$&     Inserts the matched substring.

这篇关于使用动态RegExp获取$ 1捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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