Louis
Louis

Reputation: 725

Determine if a Regex object will only accept upper case chars

In the system I am working on, regular expressions are used to enforce some specific input format for WPF Textboxes.

A behavior gets assigned a Regex object and controls the chars being typed and only let the ones valid go through. (solution similar to this article )

There is one exception however. When only upper case chars will be accepted, the chars being typed should be automatically converted to upper case instead of being rejected.

My question is:

How to elegantly determine that the regular expression, supplied in a Regex object, will only accept upper case? Is the only option to test a lower case string and then a upper case string against it? example:

if (Regex.IsMatch("THIS SHOULD PASS") && !Regex.IsMatch("this should fail")
{
    // logic to convert lower case to upper case.
}

Upvotes: 4

Views: 336

Answers (2)

ΩmegaMan
ΩmegaMan

Reputation: 31616

How to elegantly determine that the regular expression will only accept upper case?

If the pattern detection scheme detects this pattern [a-z] that would be a sign that it is to use this replace:

Regex.Replace("OmegaMan", "[a-z]", (mt) =>
 {
    return mt.Groups[0].Value.ToUpper();
 }

Output

OMEGAMAN

This operation takes any lower case letter typed and replaces it with an uppercase letter; while ignoring any upper case ones and returning the whole text back.

Upvotes: 0

TylerY86
TylerY86

Reputation: 3792

I got bored and took a shot at this.

Here's a sad but elegant implementation.

This doesn't catch unicode or hexadecimal escapes.

There's probably some other bugs. Make unit tests.

Feel free to extend it.

Upvotes: 1

Related Questions