1

我是正则表达式和 javascript 的新手,我想知道是否有人知道正则表达式用于检测输入字段是否包含以下类型的格式:

至少一个不能包含空格的字母数字和下划线 (_) 标记(例如“test”和“test_”,但不能包含“test test”)

每个标签由一个逗号分隔(例如“word1,word2,word_3,_word_4”但不是“word1,,word2,word_3,_word_4)和任何其他符号无效(如;!”'@#%^&*( )-+=.>

我的意思是这样的一个例子,这些将是有效的标签:

something1,something_2,something_something,something 这些将是无效标签:

something1%,something% 2^, !something%_&something,(*)something@+

它也应该能够只接受一个标签,也可以接受多个标签!!

谢谢。

4

2 回答 2

2

Presuming you want to accept both uppercase and lowercase characters:

^[a-zA-Z0-9_]+(,[a-zA-Z0-9_]+)*$

The mentioned site has great information about regular expressions, I recommend reading through it. For now a short explanation:

^ means beginning of the string, so that no other (possibly invalid) characters can precede it. Between [ and ] is a character class: specifying what characters may follow. [ABC] for example means an A, a B or a C. You can also specify ranges like [A-E], which means an A, B, C, D or E.

In the regular expression above I specify the range a to z, A to Z (uppercase), 0 to 9 and the single character _. The + means that the character, a group or a character from the character class preceding it must appear at least once or more.

The ( and ) group a part of the regular expression. In this case they group the , (for the comma-separated list you wanted) and a repetition of the expression so far. The * means (like the +) that the group preceding it may appear many times, but with the difference that the * makes it optional.

So, in short: this expression allows tags consisting of at least one or more characters in the range a-z, A-Z, 0-9 or the character _, optionally followed by more tags that begin with a ,, specifying the requirements for a comma-separated list :)

于 2012-05-16T18:49:48.780 回答
1

单个标签将匹配

[a-zA-Z0-9_]+

这是一个字符类,包含大写和小写的拉丁字母以及数字和下划线。这通常可以缩短为

\w+

如果您知道您的 RE 引擎不会处理 Unicode(JavaScript 就是这种情况)。不过,我现在会继续\w+

您可以通过选择单个标签和可能为零的逗号+标签来匹配多个标签

\w+(,\w+)*

如果你想验证一个完整的字符串,你应该在表达式周围放置字符串开头和字符串结尾锚:

^\w+(,\w+)*$
于 2012-05-16T18:30:15.577 回答