替换与正则表达式不匹配的字符串部分 [英] Replace part of string that doesn't match regex

查看:969
本文介绍了替换与正则表达式不匹配的字符串部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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屋!

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