gfppaste
gfppaste

Reputation: 1121

using regex to validate input formatting in C#

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!

Upvotes: 2

Views: 2140

Answers (4)

Douglas
Douglas

Reputation: 54917

  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}")

Upvotes: 2

Austin Salonen
Austin Salonen

Reputation: 50235

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);

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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}");
}

Upvotes: 5

Erwin
Erwin

Reputation: 4817

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

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

Upvotes: 2

Related Questions