Regex to restrict UPPERCASE only

laitha0 picture laitha0 · Jul 25, 2013 · Viewed 21.1k times · Source

I am stil struggling with understanding how Regex works exactly.

I am getting usernames and they are in this format:

firstname.lastname

Both names may contain special international characters and they may contain an ' or - but I just need to detect if they contain any uppercase letters so I can throw an exception.

I am using this expression

[^A-Z].[^A-Z]

It seems to me that this should work, I just don't understand why it doesn't.

I hope somebody could explain.

Thanks!

Answer

abc123 picture abc123 · Jul 25, 2013

[^A-Z] Simply means any character that isn't a capital A through capital Z.

. Means any character you should be using \. As this means the literal character .

A character group is [] and the inverse is [^] you then put the characters you want to match.

However, your regex looks like it will match only a single character that isn't a capital letter then any character then another single character that isn't a capital letter

You want to use the following:

[^A-Z]+\.[^A-Z]+

The + in regex means match the before stated 1 to infinite times.

If you are only going to have this text and no other text you should include the start of line and end of line tag so that it doesn't match long strings that include something formatted like you mentioned.

However, your regex does also match spaces and tabs.

So I would use the following:

^[^A-Z\s]+\.[^A-Z\s]+$

Regex Demo working with only lowercase

Regex Demo failing because username has uppercase letter