【问题标题】:Swear Filter Regex发誓过滤器正则表达式
【发布时间】:2012-12-10 08:08:33
【问题描述】:

我需要一个匹配某个字符串的正则表达式,并用一个符号替换它的每个字母。

所以..."Cheese" 将被 "******" 替换,但 "Pie" 将被 "***" 替换

例如:

"my pie is tasty and so is cake".replace(new RegExp(/(pizza|cake|pie|test|horseshoe)/gi), "'*' x length($1)")

(显然替换不存在)

【问题讨论】:

标签: javascript regex


【解决方案1】:

我个人认为这是一个非常糟糕的主意,因为:

  • 它会破坏有效的文本,这会惹恼有效的用户。
  • 使用拼写错误很容易欺骗过滤器,因此不会妨碍恶意用户。

但是要解决您的问题,您可以传递一个函数来替换:

var regex = /(pizza|cake|pie|test|horseshoe)/gi;
var s = "my pie is tasty and so is cake";
s = s.replace(regex, function(match) { return match.replace(/./g, '*'); });

【讨论】:

  • 还要注意关于 Scunthrope 问题的警告。
【解决方案2】:

免责声明:These filters don't work.。话虽如此,您可能希望将回调函数与replace 一起使用:

"my pie is tasty and so is cake".replace(/(pizza|cake|pie|test|horseshoe)/gi, function (match) {
    return match.replace(/./g, '*');
});

工作示例:http://jsfiddle.net/mRF9m/

【讨论】:

    【解决方案3】:

    为了防止@ThiefMaster 前面提到的classic issue,您可以考虑在模式中添加单词边界。但是,请记住,您仍然需要注意这些单词的复数形式和拼写错误形式。

    var str = 'pie and cake are tasty but not spies or protests';
    str = str.replace(/\b(pizza|cake|pie|test|horseshoe)\b/gi, function (match) {
        return match.replace(/\w/g, '*');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 2017-06-19
      • 2018-01-11
      相关资源
      最近更新 更多