Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to JavaScript parseInt in C#?

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.

like image 361
Doozer Blake Avatar asked Jun 10 '09 13:06

Doozer Blake


1 Answers

You are close.

You probably just want:

foreach (Match match in Regex.Matches(input, @"^\d+"))
{
  return int.Parse(match.Value);
}
like image 79
leppie Avatar answered Sep 25 '22 22:09

leppie