java 正则表达式,只包含小写或大写字符或两者,用于用户名验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4097601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:45:11  来源:igfitidea点击:

regular expression, only contain lower case or uppercase characters or both, for username validation

javaregex

提问by Mellon

To validate my string, I need the string only contains lowercase or uppercase or both cases mixed characters from A(a) to Z(z), and string length should be in the range from 6 to 12 characters long. What's the regular expression for this restrain?

为了验证我的字符串,我需要字符串只包含小写或大写或两种情况混合的字符,从 A(a) 到 Z(z),并且字符串长度应在 6 到 12 个字符的范围内。这个约束的正则表达式是什么?

回答by tchrist

You could use this regular expression:

你可以使用这个正则表达式:

^[\p{Lu}\p{Ll}\p{Lt}]{6,12}$

if you didn't want to penalize people for being named Fran?ois, María, or Fu?.

如果你不想因为人们被命名为 Fran?ois、María 或 Fu? 而受到惩罚。

Of course, what a string's length is in Java is less than perfectly clear, especially here, since the Patternand Matcherclasses only deal with lengths in code points (logical Unicode characters), not in the length of the string in Java's built-in but veryoxymoronically named charunits (physical 16-bit pieces of UTF-16).

当然,Java 中字符串的长度不是很清楚,尤其是在这里,因为PatternMatcher类只处理代码点(逻辑 Unicode 字符)中的长度,而不是 Java 内置的字符串长度,而是非常矛盾命名的char单位(UTF-16 的物理 16 位部分)。

That means that strings with surrogates will appears to have a different length from the standpoint of the regex engine than from many other Java classes.

这意味着从正则表达式引擎的角度来看,与许多其他 Java 类相比,带有代理项的字符串的长度似乎不同。

The regex engine has it correct, BTW.

正则表达式引擎是正确的,顺便说一句。

回答by jordanbtucker

This should work:

这应该有效:

[A-Za-z]{6,12}

However, it will match an instance of your criteria inside of the input string, so you can add the ^and $anchors to ensure your entire input string conforms to your criteria.

但是,它将匹配输入字符串内的条件实例,因此您可以添加^$锚点以确保整个输入字符串符合您的条件。

^[A-Za-z]{6,12}$

回答by cjk

Try this:

试试这个:

[a-zA-Z]{6,12}