Regex to restrict UPPERCASE only

夙愿已清 提交于 2019-12-05 12:18:51

[^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

BradW

Instead of using regex you could use this method to check for upper case characters.

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

If you want to check that there is no uppercase, you don't need dot int middle, you can use just [^A-Z] You should use start and end regex symbols and sign that this can be more then one symbol. If i remember correctly it should be something like ^[^A-Z]*$

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

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

Obviously the only correct answer is to use \p{Lu} to match an uppercase Unicode letter. There are other uppercase letters in national alphabets other than [A-Z].

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!