Reputation: 1121
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
Reputation: 54917
_
.Regex
constructor takes the pattern; the Matches
method takes the string to search.Matches
method returns a MatchCollection
. IsMatch
returns a boolean.Like so:
if (Regex.IsMatch(input, "[A-Z]{2}_[A-Z]{2}")
Upvotes: 2
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
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
Reputation: 4817
You have to put [A-Z]_[A-Z] between quotes like this:
if(r.Matches("[A-Z]_[A-Z]")
Upvotes: 2