How to remove numbers from string using Regex.Replace?

前端 未结 6 1983
星月不相逢
星月不相逢 2020-11-30 11:55

I need to use Regex.Replace to remove all numbers and signs from a string.

Example input: 123- abcd33
Example output: abcd

相关标签:
6条回答
  • 2020-11-30 12:36

    the best design is:

    public static string RemoveIntegers(this string input)
        {
            return Regex.Replace(input, @"[\d-]", string.Empty);
        }
    
    0 讨论(0)
  • 2020-11-30 12:39
    var result = Regex.Replace("123- abcd33", @"[0-9\-]", string.Empty);
    
    0 讨论(0)
  • 2020-11-30 12:40

    Try the following:

    var output = Regex.Replace(input, @"[\d-]", string.Empty);
    

    The \d identifier simply matches any digit character.

    0 讨论(0)
  • 2020-11-30 12:44

    You can do it with a LINQ like solution instead of a regular expression:

    string input = "123- abcd33";
    string chars = new String(input.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());
    

    A quick performance test shows that this is about five times faster than using a regular expression.

    0 讨论(0)
  • 2020-11-30 12:44

    As a string extension:

        public static string RemoveIntegers(this string input)
        {
            return Regex.Replace(input, @"[\d-]", string.Empty);
        }
    

    Usage:

    "My text 1232".RemoveIntegers(); // RETURNS "My text "
    
    0 讨论(0)
  • 2020-11-30 12:46

    Blow codes could help you...

    Fetch Numbers:

    return string.Concat(input.Where(char.IsNumber));
    

    Fetch Letters:

    return string.Concat(input.Where(char.IsLetter));
    
    0 讨论(0)
提交回复
热议问题