Javascript 正则表达式检查第一个字符是否为大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8274562/
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-08-24 05:23:40  来源:igfitidea点击:

Regex to check if the first character is uppercase

javascriptregex

提问by Sam

I'm trying to check that the first character of a username is capital, the following can be letters or numbers and at most 20 characters long. Can someone explain why my syntax is wrong?

我正在尝试检查用户名的第一个字符是否为大写,以下可以是字母或数字,最多 20 个字符长。有人可以解释为什么我的语法错误吗?

/^[A-z][a-z0-9_-]{3,19}$/

回答by BoltClock

Your first Z is not a capital Z.

你的第一个 Z 不是大写的 Z。

/^[A-Z][a-z0-9_-]{3,19}$/

回答by Mateen Ulhaq

Why can't you let the poor users pick their own usernames? What you should do is convert all caps to lowercase.

为什么不能让可怜的用户自己选择用户名?您应该做的是将所有大写字母转换为小写字母

"User Name".toLowerCase();


But if you are truly evil, you should change that zto a Z:

但是,如果你是真正的邪恶的,你应该更改zZ

/^[A-Z][A-Za-z0-9_-]{3,19}$/

回答by BronzeByte

I would do it like this:

我会这样做:

var firstChar = strToCheck.substring(0, 1);

if (firstChar == firstChar.toUpperCase()) {
    // it is capital :D
}

回答by Adam Rackis

Your first character needs to be A-Z, not A-z

你的第一个角色必须是A-Z,而不是A-z

So

所以

/^[A-z][a-z0-9_-]{3,19}$/

/^[A-z][a-z0-9_-]{3,19}$/

Should be

应该

/^[A-Z][a-z0-9_-]{3,19}$/

/^[A-Z][a-z0-9_-]{3,19}$/

回答by ipr101

You have a typo, the first z should be a capital -

你有一个错字,第一个 z 应该是一个大写 -

/^[A-Z][a-z0-9_-]{3,19}$/