Check if string starts with number

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)));
    }
}
    
asked by anonymous 27.07.2016 / 16:58

2 answers

3

The expression for this is quite simple:

"^\d"

In a function it looks 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;
    }
}
    
27.07.2016 / 17:16
4

Something like this?

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

I made a Fiddle .

    
27.07.2016 / 17:12