非捕获组匹配 JavaScript 正则表达式中的空白边界 [英] Non-capturing group matching whitespace boundaries in JavaScript regex
问题描述
我有这个功能可以找到整个单词并替换它们.它标识空格但不应替换它们,即不捕获它们.
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.
谢谢
推荐答案
您应该使用 捕获 组(而不是 非捕获一)在替换模式中使用替换反向引用,您还可以利用右空白边界的前瞻,这在连续匹配的情况下很方便:
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));
查看正则表达式演示.
详情
(^|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屋!