Reputation: 20001
I need to verify input which is like en-US or en-us or ar-AE I have searched net and found it bit difficult to understand and create one regular expressing on string which is no more than 5 characters in length and should be case in-sensitive.
I created one [a-z][a-z][-][a-z][a-z]
this one works fine but it doesn't check the length
it will match en-USXYZ also
Regards
Upvotes: 1
Views: 306
Reputation: 700192
You use ^
and $
to specify the start and end of the string.
^[a-z][a-z]-[a-z][a-z]$
Or using multiplier:
^[a-z]{2}-[a-z]{2}$
You would also have to include the A-Z
interval for upper case characters, unless you have specified case insensetivity for the Regex object:
^[A-Za-z]{2}-[A-Za-z]{2}$
Upvotes: 0
Reputation: 23093
\w{2}[-]\w{2}
should do the trick:
\w
-> character
{2}
-> exact 2 times
EDIT: \w
also allows number so [a-z]{2}[-][a-zA-Z]{2}
Upvotes: 0
Reputation: 25337
You should use anchors in your expression:
^[a-z][a-z][-][a-z][a-z]$
Upvotes: 0
Reputation: 336108
This is what anchors are for:
(?i)^[a-z]{2}-[a-z]{2}$
The case-insensitive option (?i)
can also be set when compiling the regex:
Regex regexObj = new Regex("^[a-z]{2}-[a-z]{2}$", RegexOptions.IgnoreCase);
Upvotes: 4