简体   繁体   中英

Regex to check if string contains only one uppercase

What is the regex to make sure that a given string contains exactly one uppercase letter? if the string contains more than one i dont want it to be matched.

  • just 1 Uppercase character

I know the patterns for individual sets namely [az] , [AZ] , \d and _|[^\w] (I got them correct, didn't I?).

But how do I make them to match only with strings (in java) that only contains 1 uppercase?

You may use this regex with 2 negated character classes:

^[^A-Z]*[A-Z][^A-Z]*$

Above regex will support ASCII upper case letters only. If you want to match unicode letters then use:

^\P{Lu}*\p{Lu}\P{Lu}*$

RegEx Demo 2 RegEx Demo

Here:

  • \P{Lu}* : Match 0 or more non-uppercase unicode letters
  • \p{Lu} : Match an uppercase unicode letter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM