Check if string starts with number

Asked

Viewed 817 times

4

I need to check if a string starts with numbers. I want to do this using Regex in c#

public static class StringExtensao
{
    public static bool ComecaComNumero(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;
        return char.IsNumber(Convert.ToChar( str.Substring(0,1)));
    }
}

2 answers

4

Something like that?

public static bool IsNumber(string str)
{
    return new Regex(@"^[0-9]+").IsMatch(str);
}

I made a Fiddle.

3


The expression for this is very simple:

"^\d"

In a function is something like this:

using System;
using System.Text.RegularExpressions;

class Program
{
    bool ComecaComNumero(String s)
    {
        Regex r = new Regex(@"^\d");
        return r.Match(s).Success;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.