【问题标题】:Filter out chars not in a set过滤掉不在集合中的字符
【发布时间】:2013-08-01 05:34:21
【问题描述】:

我正在尝试过滤通过我的系统传递的所有字符串,以便我只发送有效字符。

以下是允许的。

a-z
A-Z
"-" (hypen, 0x24)
" " (space, 0x20)
"’" (single quote, 0x27)
"~" (tilde, 0x7E)

现在我可以想出一个在这个集合中搜索字符的正则表达式。但我需要的是一个与该集合中的字符匹配的正则表达式,因此我可以用任何内容替换它们。

有什么想法吗?

【问题讨论】:

    标签: regex perl regex-negation


    【解决方案1】:

    这是您可以做到的一种方法。你标记了 Perl,所以我会给你一个 perlish 解决方案:

    my $string = q{That is a ~ v%^&*()ery co$ol ' but not 4 realistic T3st};
    print $string . "\n";
    $string =~ s{[^-a-zA-Z '~]}{}g;
    print $string . "\n";
    

    打印:

    That is a ~ v%^&*()ery co$ol ' but not 4 realistic T3st
    That is a ~ very cool ' but not  realistic Tst
    

    说清楚:

    $string =~ s{[^-a-zA-Z '~]}{}g;
    

    匹配[,] 括号内不是[^..] 的字符,并将它们替换为空。替换末尾的 g 标志用于替换超过 1 个字符。

    【讨论】:

      【解决方案2】:

      匹配你提到的字符串的正则表达式是:

      [a-zA-Z\\-~]|\x27
      

      更多信息请参考http://www.regular-expressions.info/quickstart.html

      【讨论】:

        猜你喜欢
        • 2015-12-28
        • 1970-01-01
        • 1970-01-01
        • 2017-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-26
        • 1970-01-01
        相关资源
        最近更新 更多