Regular expression restricts only UPPERCASE

I try to understand how Regex works.

I get user names and they are in this format:

firstname.lastname 

Both names can contain special international characters, and they can contain "or", but I just need to determine if they contain any capital letters, so I can throw an exception.

I use this expression

 [^AZ].[^AZ] 

It seems to me that this should work, I just do not understand why this is not so.

Hope someone can explain.

Thanks!

+5
source share
5 answers

[^AZ] Just means any symbol that is not capital A through capital Z.

. Means any character you must use \. Since it means a letter symbol .

The character group is [] , and the reverse is [^] , then you put the characters you want to match.

However, your regular expression looks like it will only match one character that is not a capital letter, then any character, then another character that is not a capital letter

You want to use the following:

[^AZ]+\.[^AZ]+

+ in regular expression means matching with the specified 1 to infinity.

If you have only this text and no other text, you should include the beginning of the line and the end of the line so that it does not correspond to long lines that include something formatted as you mentioned.

However, your regex also matches spaces and tabs.

Therefore, I would use the following:

^[^AZ\s]+\.[^AZ\s]+$

Regex Demo only works with lowercase

Regex Demo error because username is uppercase

+8
source

Instead of using a regular expression, you can use this method to validate uppercase characters.

 public static bool checkStringForUpperCase(string s) { for (int i = 0; i < s.Length; i++) { if (char.IsUpper(s[i])) return false; } return true; } 
+4
source

If you want to check that there are no uppercase letters, you do not need an int middle point, you can use only [^AZ] You must use the start and end characters of regular expressions and sign that it can be more than one character. If I remember correctly, it should be something like ^[^AZ]*$

+3
source

If you only want to check if it contains uppercase or not. Try it.

  string test = @"Test"; string test2 = "test"; bool result = test.Any(x=>char.IsUpper(x)); //true result = test2.Any(x => char.IsUpper(x));//false 
0
source

Obviously, the only correct answer is to use \p{Lu} to match the Unicode capital letter. There are other capital letters in national alphabets besides [AZ] .

0
source

Source: https://habr.com/ru/post/1493462/


All Articles