简体   繁体   English

正则表达式检查字符串是否仅包含一个大写字母

[英]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?).我知道单个集合的模式,即[az][AZ]\d_|[^\w] (我猜对了,不是吗?)。

But how do I make them to match only with strings (in java) that only contains 1 uppercase?但是如何使它们仅与仅包含 1 个大写字母的字符串(在 java 中)匹配?

You may use this regex with 2 negated character classes:您可以将此正则表达式与 2 个否定字符类一起使用:

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

Above regex will support ASCII upper case letters only.以上正则表达式将仅支持 ASCII 大写字母。 If you want to match unicode letters then use:如果要匹配 unicode 字母,请使用:

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

RegEx Demo 2 RegEx Demo正则表达式演示 2正则表达式演示

Here:这里:

  • \P{Lu}* : Match 0 or more non-uppercase unicode letters \P{Lu}* :匹配 0 个或多个非大写 unicode 字母
  • \p{Lu} : Match an uppercase unicode letter \p{Lu} :匹配大写 unicode 字母

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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