Search code examples
javac#regexmaxlengthdigit

Length of specific substring


I check if my string begins with number using

if(RegEx(IsMatch(myString, @"\d+"))) ...

If this condition holds I want to get the length of this "numeric" substring that my string begins with.

I can find the length checking if every next character is a digit beginning from the first one and increasing some counter. Is there any better way to do this?


Solution

  • To check if my string begins with number, you need to use pattern ^\d+.

    string pattern = @"^\d+";
    MatchCollection mc = Regex.Matches(myString, pattern);
    if(mc.Count > 0)
    {
      Console.WriteLine(mc[0].Value.Length);
    }