简体   繁体   English

正则表达式。替换不适用于分隔符

[英]Regex.Replace is not working with separators

I just want to replace with String.Empty if any Separators found in a given string. 我只想用String.Empty替换,如果在给定的字符串中找到任何分隔符。

class Program
{
    private const string Separators = "-(). ";
    static void Main(string[] args)
    {
        var number = Format("88 88-88)8.8(88");
    }

    public static string Format(string number)
    {
        return Regex.Replace(number, Separators, string.Empty);
    }
}

Expected is : 8888888888 But was 88 88-88)8.8(88 . Did i miss something here. 预期为: 8888888888但当时是88 88-88)8.8(88 。我在这里错过了什么吗?

Edit : if use 编辑 :如果使用

Separators.ToCharArray().ToList().ForEach(c => { number = number.Replace(c.ToString(), string.Empty);});

it works. 有用。 But it could be better if i achieve with Regex.Replace . 但是如果我用Regex.Replace实现的话可能会更好。

When you are using a regular expression some characters have certain meanings. 使用正则表达式时,某些字符具有某些含义。 A dot means "any character", a dash means a range as in 0-9. 点表示“任何字符”,破折号表示范围为0-9。 I've escaped the characters and put them in a character set [] which means "any one in this set". 我已将这些字符转义,然后将它们放在字符集[]中,这意味着“该集中的任何人”。 I also renamed your Separators variable to better reflect what it is now. 我还重命名了Separators变量,以更好地反映它的含义。

Try this instead: 尝试以下方法:

class Program
{
    private const string SeparatorsRegex = @"[\-()\. ]";
    static void Main(string[] args)
    {
        var number = Format("88 88-88)8.8(88");
    }

    public static string Format(string number)
    {
        return Regex.Replace(number, SeparatorsRegex, string.Empty);
    }
}

Tested it in Expresso and this worked as expected. 在Expresso中对其进行了测试,并且效果达到了预期。 Its a great tool for regex dev: 对于正则表达式开发人员来说,这是一个很棒的工具:

(Ignore the terrible site design, it is a good util honest :P ) (忽略可怕的网站设计,这是一个很好的实用诚实:P)

A further note, is that if you just want to strip everything that isnt a number then you could actually use this: 还有一点需要注意的是,如果您只想剥离所有不包含数字的内容,则可以使用以下代码:

class Program
{
    private const string StripNonNumbersRegex = @"[^\d]";
    static void Main(string[] args)
    {
        var number = Format("88 88-88)8.8(88");
    }

    public static string Format(string number)
    {
        return Regex.Replace(number, StripNonNumbersRegex, string.Empty);
    }
}

Regex.Replace() works on patterns, not separators. Regex.Replace()适用于模式,而不适用于分隔符。 You are confusing it with String.Replace() . 您将其与String.Replace()混淆了。

String.Replace(source, "-", string.empty) will work, but you will need to run this once per character. String.Replace(source,“-”,string.empty)可以使用,但是您需要每个字符运行一次。 Regex.Replace(source, pattern, string.empty) will work better, but you need to use a RegEx pattern , not simple list the characters. Regex.Replace(source,pattern,string.empty)会更好,但是您需要使用RegEx pattern ,而不是简单列出字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM