2

This is a super basic question (I am brain dead today):

How do I validate in input using regexes, to see: 1) if the input is in a certain form 2) if the input is all caps (just casting the input to caps is not feasible for this)

I want ot make sure my inputs are in the form XX_XX. Here isi what I have:

public bool IsKosher(string input)
{
    Regex r = new Regex(input);
    if(r.Matches([A-Z]_[A-Z]))
    {
        return true;
    }
    return false;     
}

Any ideas why it's not compiling?

Thank you!

4 Answers 4

5

You are missing double quotes, you put parameters in wrong places, and you do not need an if statement:

public bool IsKosher(string input) {
    return Regex.IsMatch(input, "[A-Z]{2}_[A-Z]{2}");
}
Sign up to request clarification or add additional context in comments.

Comments

3

Quotes? A missing closing parenthesis? Matches not returning a boolean? Swapping string parameters? All will cause your code not to compile.

Though you may want this if it is "XX_XX":

var r = new Regex("[A-Z]{2}_[A-Z]{2}");
return r.IsMatch(input);

Comments

2

You have to put [A-Z]_[A-Z] between quotes like this:

if(r.Matches("[A-Z]_[A-Z]")

Comments

2
  1. Quotes.
  2. Two characters on either side of the _.
  3. The Regex constructor takes the pattern; the Matches method takes the string to search.
  4. The Matches method returns a MatchCollection. IsMatch returns a boolean.

Like so:

if (Regex.IsMatch(input, "[A-Z]{2}_[A-Z]{2}")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.