【问题标题】:javascript regular expression to replace special characters, but allow a whitelist, using xregexpjavascript正则表达式替换特殊字符,但允许白名单,使用xregexp
【发布时间】:2015-12-16 15:51:55
【问题描述】:

我想替换字符串中的大多数特殊字符(在 javascript 中),但允许一些特殊情况,如 c++、c# 等。我已经尝试过 node.js 中的 xregexp 库,我认为我能够删除所有非字母和数字。我也想允许所有外语字母。这是我目前所拥有的:

  var str = "I do programming in c++ and sometimes c#, but + and # should be removed";
  regex = XRegExp('[^\\s\\p{N}\\p{L}]+', 'g');
  var replaced = XRegExp.replace(str, regex, "");
  console.log(replaced); 

这个输出

I do programming in c and sometimes c, but and should be removed

我需要使用允许的单词创建某种列表,例如 c++ 和 c#。期望的输出是:

I do programming in c++ and sometimes c#, but and should be removed

【问题讨论】:

    标签: javascript regex xregexp


    【解决方案1】:

    您可以在捕获组中使用替换,然后在替换模式中使用反向引用来恢复此文本:

    var str = "I do programming in c++ and sometimes c#, but + and # should be removed";
    regex = XRegExp('(\\b(?:c[+]{2}|c#)(?!\\w))|[^\\s\\p{N}\\p{L}]+', 'ig');
    //               ^-- capture group 1 -----^                        ^  
    var replaced = XRegExp.replace(str, regex, "$1");
    //                                          ^^
    console.log(replaced);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/2.0.0/xregexp-all-min.js"></script>

    注意我添加了一个i 标志以使模式不区分大小写,\b 在交替的开头只匹配单词边界(因为c++c# 以字母开头(单词字符),以及确保+# 之后没有单词字符的前瞻(?!\w)\b 在这里不起作用,因为它们不是单词字符)。

    【讨论】:

    • 实际上,它还删除了逗号(您提供了错误的当前输出)。我想您还需要将\\p{P} 添加到您的否定字符类中。
    • 完美运行,抱歉输出错误,逗号应该去掉,谢谢解释!
    • 我在将其修改为也不能替换 .NET 时遇到了一些麻烦,你能举个例子吗?
    • regex = XRegExp('(\\B\\.NET\\b|\\b(?:c[+]{2}|c#)(?!\\w))|[^\\s\\p{N}\\p{L}]+', 'ig');
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多