Saturday, April 13, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  18] [ 1]  / answers: 1 / hits: 22331  / 15 Years ago, wed, june 10, 2009, 12:00:00

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.


More From » c#

 Answers
267

You are close.



You probably just want:



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

[#99347] Thursday, June 4, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
iyannae

Total Points: 147
Total Questions: 88
Total Answers: 120

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
;