替换与正则表达式不匹配的字符串部分 [英] Replace part of string that doesn't match regex
问题描述
我正在尝试使用JavaScript替换不匹配正则表达式模式的字符串部分。这在功能上等同于在GNU grep中使用 -v
标志来反转结果。以下是一个示例:
I am attempting to replace parts of a string that don't match a regular expression pattern using JavaScript. This is functionally equivalent to using the -v
flag in a GNU grep to invert results. Here is an example:
// I want to replace all characters that don't match "fore"
// in "aforementioned" with "*"
'aforementioned'.replace(new RegExp(pattern, 'i'), function(match){
//generates a string of '*' that is the length of match
return new Array(match.length).join('*');
});
我正在寻找模式的正则表达式
。这与(前)
相反。我已经四处搜索但未能实现任何相关问题的答案以满足我的需求。无论如何,这是一个列表,也许它会指出我们正确的方向:
I am looking for a regex for pattern
. This would be something like the opposite of (fore)
. I've searched around but haven't been able to implement any related question's answers to fit my needs. Here is a list anyway, maybe it will point us in the right direction:
- Regular Expressions and negating a whole character group
- Match everything except for specified strings
推荐答案
如果我理解正确,这应该是一种可能的解决方案:
If I understand you correctly, this should be one possible solution:
'aforementioned'.replace(new RegExp(pattern + '|.', 'gi'), function(c) {
return c === pattern ? c : '*';
});
>> "*fore*********"
这篇关于替换与正则表达式不匹配的字符串部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!