Is there an equivalent to JavaScript parseInt in C#?

Doozer Blake picture Doozer Blake · Jun 10, 2009 · Viewed 21.4k times · Source

I was wondering if anyone had put together something or had seen something equivalent to the JavaScript parseInt for C#.

Specifically, i'm looking to take a string like:

123abc4567890

and return only the first valid integer

123

I have a static method I've used that will return only the numbers:

public static int ParseInteger( object oItem )
    {
        string sItem = oItem.ToString();

        sItem = Regex.Replace( sItem, @"([^\d])*", "" );

        int iItem = 0;

        Int32.TryParse( sItem, out iItem );

        return iItem;
    }

The above would take:

ParseInteger( "123abc4567890" );

and give me back

1234567890

I'm not sure if it's possible to do with a regular expression, or if there is a better method to grab just the first integer from the string.

Answer

leppie picture leppie · Jun 10, 2009

You are close.

You probably just want:

foreach (Match match in Regex.Matches(input, @"^\d+"))
{
  return int.Parse(match.Value);
}