Is there an equivalent to JavaScript parseInt in C#?
Asked Answered
D

7

11

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.

Denitadenitrate answered 10/6, 2009 at 13:8 Comment(1)
Thanks for all the answers, they were all very helpful. I marked leppie's as accepted because it was first by a bit and did work. I took his and ran with that with some modifications. Jon Skeet's is definitely the most complete. Thanks again!Denitadenitrate
P
18

You are close.

You probably just want:

foreach (Match match in Regex.Matches(input, @"^\d+"))
{
  return int.Parse(match.Value);
}
Physicality answered 10/6, 2009 at 13:13 Comment(4)
That will convert "ab12cd" to 12 won't it? That may well be the desired behaviour - I'm not sure. I'm only asking because my version only works if the number is at the start of the string.Periscope
Ahh, you are right, a ^ at the start of the RE qould probably be good enough :) ThanksPhysicality
leppie: I wasn't suggesting that was required, so much as that your implementation's behaviour may well be desirable, and I wanted to check :)Periscope
You can't use var in that foreach because Regex.Matches returns a MatchCollection that is a non generic ICollection. As it happens I blogged about this yesterday: alicebobandmallory.com/articles/2009/06/09/…Foamy
P
9

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);
    }
}
Periscope answered 10/6, 2009 at 13:16 Comment(5)
can you tell me, if there's any difference in the runtime/performance between yours, accepted and mine? does internally regex works exactly the way i posted?Thieve
You'd have to benchmark it to find out the performance. I don't know the details of how .NET regexes are implemented. It will depend on the options though - in this case I haven't specified that it should be compiled, which would probably help performance after the initial hit of compilation.Periscope
as you wrote a benchmark-suite: would you possibly run this test in some free time for me?Thieve
That benchmark suite is still very much under development, I'm afraid. With the revisions for C# in Depth for the second edition, I don't really have any spare time for this at the moment. Sorry :(Periscope
ah ... that's ok ... i'll have a look at it on my own, when i got time!Thieve
H
2

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
(e.g., asb12354 -> 12354) and both signed integer cases (e.g. + or -)

Houlberg answered 10/6, 2009 at 13:24 Comment(0)
G
1
    public static int ParseInteger( object oItem )
    {
            int iItem = 0;
            if (oItem != null) {
                    Int32.TryParse( Regex.Match( oItem.ToString(), @"\d+" ).Value, out iItem );
            }
            return iItem;
    }
Genocide answered 10/6, 2009 at 13:20 Comment(0)
A
0

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.

Alberik answered 10/6, 2009 at 13:17 Comment(0)
Z
0
int nr = Int32.Parse(yourstring);
Zitvaa answered 15/3, 2013 at 10:29 Comment(0)
S
-3

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.

Scagliola answered 28/5, 2012 at 22:30 Comment(2)
All of these will fail given the sample string "123abc4567890", hence the need for something custom.Denitadenitrate
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.Scagliola

© 2022 - 2024 — McMap. All rights reserved.