Parse a number from a string with non-digits in between

c#

Solution

There's no such function, at least none I know of. But one method would be to use a regular expression to remove everything that is not a number:

using System;
using System.Text.RegularExpressions;

int result =
    // The Convert (System) class comes in pretty handy every time
    // you want to convert something.
    Convert.ToInt32(
        Regex.Replace(
            "12ACD",  // Our input
            "[^0-9]", // Select everything that is not in the range of 0-9
            ""        // Replace that with an empty string.
    ));

This function will yield `12` for `12ABC`, so if you need to be able to process negative numbers, you'll need a different solution. It is also not safe, if you pass it only non-digits it will yield a `FormatException`. Here is some example data:

"12ACD"  =>  12
"12A5"   =>  125
"CA12A"  =>  12
"-12AD"  =>  12
""       =>  FormatException
"AAAA"   =>  FormatException

A little bit more verbose but safer approach would be to use `int.TryParse()`:

using System;
using System.Text.RegularExpression;

public static int ConvertToInt(String input)
{
    // Replace everything that is no a digit.
    String inputCleaned = Regex.Replace(input, "[^0-9]", "");

    int value = 0;

    // Tries to parse the int, returns false on failure.
    if (int.TryParse(inputCleaned, out value))
    {
        // The result from parsing can be safely returned.
        return value;
    }

    return 0; // Or any other default value.
}

Some example data again:

"12ACD"  =>  12
"12A5"   =>  125
"CA12A"  =>  12
"-12AD"  =>  12
""       =>  0
"AAAA"   =>  0

Or if you only want the first number in the string, basically stopping at meeting something that is not a digit, we suddenly also can treat negative numbers with ease:

using System;
using System.Text.RegularExpression;

public static int ConvertToInt(String input)
{
    // Matches the first numebr with or without leading minus.
    Match match = Regex.Match(input, "-?[0-9]+");

    if (match.Success)
    {
        // No need to TryParse here, the match has to be at least
        // a 1-digit number.
        return int.Parse(match.Value);
    }

    return 0; // Or any other default value.
}

And again we test it:

"12ACD"  =>  12
"12A5"   =>  12
"CA12A"  =>  12
"-12AD"  =>  -12
""       =>  0
"AAAA"   =>  0

Overall, if we're talking about user input I would consider not accepting invalid input at all, only using `int.TryParse()` without some additional magic and on failure informing the user that the input was suboptimal (and maybe prompting again for a valid number).

Problem

I am working on .NET project and I am trying to parse only the numeric value from string. For example, ``` string s = "12ACD"; int t = someparefun(s); print(t) //t should be 12 ``` A couple assumptions are - The string pattern always will be number follow by characters. - The number portion always will be either one or two digits value. Is there any C# predefined function to parse the numeric value from string?

Original source

Related problems