Search code examples
c#regexstringisinteger

How do you check if a string contains an int at a specific location?


I want to make sure that a folder has the correct name format before proceeding. The code below demonstrates what I am trying to do, although {char.IsDigit} doesn't work. I would like to replace char.IsDigit with something that means "any digit".

if(versionName == $"Release {char.IsDigit}.{char.IsDigit}.{char.IsDigit}.{char.IsDigit}")
{
    //Do something
}

Thanks


Solution

  • You want to use Regex.IsMatch with a regex like:

    if(Regex.IsMatch(versionName, @"^Release \d\.\d\.\d\.\d$"))
    {
        //Do something
    }
    

    Note \d just matches a single digit, if there can be more than 1 digits

    @"^Release \d+\.\d+\.\d+\.\d+$"
    

    And tightening it all up:

    @"^Release \d+(?:\.\d+){3}$"
    

    See the regex demo and its graph:

    enter image description here