Abhishek Kumar
Abhishek Kumar

Reputation: 352

String format Check gives unexpected result (Regex)

I want to check format of a string which is ABC-nnn, where ABC represents alphabets (English) in capital letters. nnn represents triple digit number for example 123 or 001 or 012 A complete example would be FBI-026. I used regex for that and below is my code.

public bool IsSubstringMatchingFormat(int numberOfLettersBeforeHyphen, int numberOfNumbersAfterHyphen, string stringToMatch)
{
    Regex regex = new Regex($@"^[A-Z]{numberOfLettersBeforeHyphen}-\d{numberOfNumbersAfterHyphen}");
    return regex.IsMatch(stringToMatch);
} 

I call it IsSubstringMatchingFormat(3, 3, "SMB-123") but it returns false. Please provide your insight.

Upvotes: 1

Views: 53

Answers (3)

Chris
Chris

Reputation: 27599

Have you actually checked what the string you are passing into the regex looks like? ie evaluate $@"^[A-Z]{numberOfLettersBeforeHyphen}-\d{numberOfNumbersAfterHyphen}"and see if that is the regex you want? I can tell you that it isn't because it will end up being ^[A-Z]3-\d3 which does not do what you want.

What I think you'll want is:

$@"^[A-Z]{{{numberOfLettersBeforeHyphen}}}-\d{{{numberOfNumbersAfterHyphen}}}"

This adds the escaped curly braces back into your regex to give:

^[A-Z]{3}-\d{3}

The equivalent of this using String.Format would be:

String.Format(
    @"^[A-Z]{{{0}}}-\d{{{1}}}",
    numberOfLettersBeforeHyphen, 
    numberOfLettersAfterHyphen);

Upvotes: 4

Kell
Kell

Reputation: 3317

The {} are being removed when you format. Try this:

        public static bool IsSubstringMatchingFormat(int numberOfLettersBeforeHyphen, int numberOfNumbersAfterHyphen, string stringToMatch)
    {
        var expre = @"^[A-Z]{numberOfLettersBeforeHyphen}-\d{numberOfNumbersAfterHyphen}";//
        expre = expre.Replace("numberOfLettersBeforeHyphen", numberOfLettersBeforeHyphen.ToString())
            .Replace("numberOfNumbersAfterHyphen", numberOfNumbersAfterHyphen.ToString());
        Regex regex = new Regex(expre);
        return regex.IsMatch(stringToMatch);
    } 

Upvotes: 0

Your curly braces are being consumed by the string interpolation and are not making it into the regex. If you try to print the regex, you'll see it's something like

^[A-Z]3-\d3

Which is something else entirely.

Upvotes: 0

Related Questions