字母数字和下划线的正则表达式 [英] Regular Expression for alphanumeric and underscores

查看:137
本文介绍了字母数字和下划线的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个正则表达式来检查字符串是否只包含大小写字母、数字和下划线.

I would like to have a regular expression that checks if a string contains only upper and lowercase letters, numbers, and underscores.

推荐答案

要匹配那些字符(或空字符串)的字符串,请尝试

To match a string that contains only those characters (or an empty string), try

"^[a-zA-Z0-9_]*$"

这适用于 .NET 正则表达式,可能也适用于许多其他语言.

This works for .NET regular expressions, and probably a lot of other languages as well.

分解:

^ : start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
] : end of character group
* : zero or more of the given characters
$ : end of string

如果您不想允许空字符串,请使用 + 而不是 *.

If you don't want to allow empty strings, use + instead of *.

正如其他人指出的那样,一些正则表达式语言有 [a-zA-Z0-9_] 的简写形式.在 .NET 正则表达式语言中,您可以打开 ECMAScript 行为并使用 \w 作为速记(产生 ^\w*$^\w+$).请注意,在其他语言中,默认情况下,在 .NET 中,\w 范围更广,并且也会匹配其他类型的 Unicode 字符(感谢 Jan 指出这一点).因此,如果您真的打算匹配这些字符,那么使用显式(更长)的形式可能是最好的.

As others have pointed out, some regex languages have a shorthand form for [a-zA-Z0-9_]. In the .NET regex language, you can turn on ECMAScript behavior and use \w as a shorthand (yielding ^\w*$ or ^\w+$). Note that in other languages, and by default in .NET, \w is somewhat broader, and will match other sorts of Unicode characters as well (thanks to Jan for pointing this out). So if you're really intending to match only those characters, using the explicit (longer) form is probably best.

这篇关于字母数字和下划线的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆