JavaScript正则表达式中的非捕获组匹配空白边界 [英] Non-capturing group matching whitespace boundaries in JavaScript regex

查看:42
本文介绍了JavaScript正则表达式中的非捕获组匹配空白边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有此功能,可以查找整个单词并应替换它们.它标识了空格,但不应替换它们,即不捕获它们.

I have this function that finds whole words and should replace them. It identifies spaces but should not replace them, ie, not capture them.

function asd (sentence, word) {
     str = sentence.replace(new RegExp('(?:^|\\s)' + word + '(?:$|\\s)'), "*****");
     return str;
};

然后我有以下字符串:

var sentence = "ich mag Äpfel";
var word = "Äpfel";

结果应该类似于:

"ich mag *****" 

而非:

"ich mag*****"

我得到了后者.

如何使它识别空格,但在替换单词时忽略空格?

How can I make it so that it identifies the space but ignores it when replacing the word?

起初这似乎是重复的,但是我没有找到这个问题的答案,这就是为什么我要问这个问题.

At first this may seem like a duplicate but I did not find an answer to this question, that's why I'm asking it.

谢谢

推荐答案

您应该使用 captureing 组(而不是 non-captureing )放回匹配的空格一个),并在替换模式中使用替换后向引用,并且您还可以利用超前查询来找到正确的空白边界,这在连续匹配的情况下非常方便:

You should put back the matched whitespaces by using a capturing group (rather than a non-capturing one) with a replacement backreference in the replacement pattern, and you may also leverage a lookahead for the right whitespace boundary, which is handy in case of consecutive matches:

function asd (sentence, word) {
     str = sentence.replace(new RegExp('(^|\\s)' + word + '(?=$|\\s)'), "$1*****");
     return str;
};
var sentence = "ich mag Äpfel";
var word = "Äpfel";
console.log(asd(sentence, word));

请参见 regex演示.

详细信息

  • (^ | \ s)-第1组(后来在替换模式中借助 $ 1 占位符进行引用):与任一开始匹配的捕获组字符串或空格
  • Äpfel-搜索词
  • (?= $ | \ s)-正向超前,需要在当前位置的右侧紧跟着字符串或空格的结尾.
  • (^|\s) - Group 1 (later referred to with the help of a $1 placeholder in the replacement pattern): a capturing group that matches either start of string or a whitespace
  • Äpfel - a search word
  • (?=$|\s) - a positive lookahead that requires the end of string or whitespace immediately to the right of the current location.

注意:如果 word 可以包含特殊的正则表达式元字符,请转义它们:

NOTE: If the word can contain special regex metacharacters, escape them:

function asd (sentence, word) {
     str = sentence.replace(new RegExp('(^|\\s)' + word.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '(?=$|\\s)'), "$1*****");
     return str;
};

这篇关于JavaScript正则表达式中的非捕获组匹配空白边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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