问题

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



解决方法

要匹配仅包含这些字符(或空字符串)的字符串,请尝试

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

这适用于.NET正则表达式,可能还有很多其他语言.

分解:

^ : 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

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

EDIT 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.




相关问题推荐