Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
515 views
Welcome To Ask or Share your Answers For Others

1 Answer

To 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_]的简写形式。)

In the .NET regex language, you can turn on ECMAScript behavior and use \w as a shorthand (yielding ^\w*$ or ^\w+$ ).

(在.NET正则表达式语言中,您可以打开ECMAScript行为并使用\w作为简写(产生^\w*$^\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).

(请注意,在其他语言中,默认情况下在.NET中, \w稍微宽泛一些,并且还会匹配其他类型的unicode字符(感谢Jan指出这一点)。)

So if you're really intending to match only those characters, using the explicit (longer) form is probably best.

(因此,如果您真的打算匹配这些字符,那么使用显式(更长)形式可能是最好的。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...