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.
You are close.
You probably just want:
foreach (Match match in Regex.Matches(input, @"^\d+"))
{
return int.Parse(match.Value);
}
Here's a complete example. It will throw an exception if you don't give it a valid string - you can change this behaviour by not explicitly throwing an exception in ParseInteger
, and using int.TryParse
instead.
Note that it allows a leading - sign as well, but not a leading +. (Again, easy to change.)
Also note that although I've got three test cases for success situations, I haven't got any test cases for failure.
Finally, it won't match "abc123def". If you want it to, remove the ^ from the regex.
using System;
using System.Text;
using System.Text.RegularExpressions;
class Test
{
static void Main(string[] args)
{
Check("1234abc", 1234);
Check("-12", -12);
Check("123abc456", 123);
}
static void Check(string text, int expected)
{
int actual = ParseInteger(text);
if (actual != expected)
{
Console.WriteLine("Expected {0}; got {1}", expected, actual);
}
}
private static readonly Regex LeadingInteger = new Regex(@"^(-?\d+)");
static int ParseInteger(string item)
{
Match match = LeadingInteger.Match(item);
if (!match.Success)
{
throw new ArgumentException("Not an integer");
}
return int.Parse(match.Value);
}
}
A slight change to Jon Skeet's excellent solution is in order.
I would change the regex to (as mentioned by Jon):
@"^([^\\d]+)?(+|-)?\\d+"
This allows for the case of leading characters ahead of the first occurrence of a digit
(eg, asb12354
-> 12354
) and both signed integer cases (eg +
or -
)
public static int ParseInteger( object oItem )
{
int iItem = 0;
if (oItem != null) {
Int32.TryParse( Regex.Match( oItem.ToString(), @"\d+" ).Value, out iItem );
}
return iItem;
}
int nr = Int32.Parse(yourstring);
You could use this RegEx ("\\A\\d+") to find numbers at the beginning of a string.
You can then use int.Parse() to convert that string into an actual integer.
You DON'T have to write your own int parse function!!!!
I know this thread is pretty old. but there are some simple way to do this:
int.Parse(urString);
use short.Parse(urString); //if you want a short
Or: //use those depend on your situation:
Convert.ToInt16();
Convert.ToInt32();
Convert.ToInt64();
NOTE:
I am answering your Topic Question "Is there an equivalent to JavaScript parseInt in C#?", just give you some idea, NOT write your code for you. You need to first do a filtering on 'Alphabetical Characters', you can do it with Regular Expression or a simple string.Replace, or up to you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.