我想有一个正则表达式,检查字符串是否只包含大写和小写字母,数字和下划线。
ask by translate from soTo match a string that contains only those characters (or an empty string), try
(要匹配仅包含这些字符(或空字符串)的字符串,请尝试)
"^[a-zA-Z0-9_]*$"
This works for .NET regular expressions, and probably a lot of other languages as well.
(这适用于.NET正则表达式,也可能适用于许多其他语言。)
Breaking it down:
(打破它:)
^ : 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 *.
(如果您不想允许空字符串,请使用+而不是*。)
EDIT As others have pointed out, some regex languages have a shorthand form for [a-zA-Z0-9_]
.
(编辑正如其他人所指出的,一些正则表达式语言有[a-zA-Z0-9_]
的简写形式。)
\w
as a shorthand (yielding ^\w*$
or ^\w+$
). (在.NET正则表达式语言中,您可以打开ECMAScript行为并使用\w
作为简写(产生^\w*$
或^\w+$
)。)
\w
is somewhat broader, and will match other sorts of unicode characters as well (thanks to Jan for pointing this out). (请注意,在其他语言中,默认情况下在.NET中, \w
稍微宽泛一些,并且还会匹配其他类型的unicode字符(感谢Jan指出这一点)。)
(因此,如果您真的打算只匹配这些字符,那么使用显式(更长)形式可能是最好的。)