Learning
Learning

Reputation: 20001

Regular Expression in C#

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

Answers (7)

Guffa
Guffa

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

Christoph Fink
Christoph Fink

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

Mithrandir
Mithrandir

Reputation: 25337

You should use anchors in your expression:

^[a-z][a-z][-][a-z][a-z]$

Upvotes: 0

Samich
Samich

Reputation: 30095

Use such one:

^[a-z]{2}-[a-z]{2}$

Upvotes: 4

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use this regular expression:

^[a-z]{2}-[a-z]{2}$

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

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

atoMerz
atoMerz

Reputation: 7672

Try this:

^[a-z][a-z][-][a-z][a-z]$

Upvotes: 3

Related Questions