类似于facebook的个人资料徽章的Javascript正则表达式

时间:2012-05-18 09:55:13

标签: javascript regex

我正在寻找一个正则表达式来创建一个符合以下条件的字符串:

  • 可以是可变长度(最多30个字符)
  • 只能包含字母数字(a-z,A-Z)和数字字符(0-9)
  • 只能包含这些特殊字符“ - ”,“。”字符串中的任何地方
  • 必须以字母数字或数字开头,而不是特殊字符
  • 必须至少5个字符

“徽章”字符串将需要在网站的网址中使用,任何有关此字符串是否正常的建议都将受到赞赏。

谢谢

3 个答案:

答案 0 :(得分:1)

RegExp不会创建用于验证或匹配它们的字符串。这是你的意思吗?

根据约束验证字符串的RegExp将是

  /^[a-z0-9][-,\.a-z0-9]{4,29}$/i

说明:

   /^                  Start of string
   [a-z0-9]            One character in the set a-z or 0-9 
                       (A-Z also valid since we specify flag i at the end
   [-,\.a-z0-9]{4,29}  A sequence of at least 4 and no more than 29 characters
                       in the set. Note . is escaped since it has special meaning
   $                   End of string (ensures there is nothing else
   /i                  All matches are case insensitive a-z === A-Z

答案 1 :(得分:0)

^\w[\w-,\.]{4}[\w-,\.]{0,25}$

这转换为:

  

匹配以字母数字开头的字符串,然后匹配4个有效字符,   然后最多25个有效字符。有效的是字母数字“,”“ - ”或   “”

以下PowerShell脚本为此规则提供了单元测试。

$test = "^\w[\w-,\.]{4}[\w-,\.]{0,25}$"

# Test length rules.
PS > "abcd" -match $test # False: Too short (4 chars)
False
PS > "abcde" -match $test # True: 5 chars
True
PS > "abcdefghijklmnopqrstuvwxyzabcd" -match $test # True: 30 chars
True
PS > "abcdefghijklmnopqrstuvwxyzabcde" -match $test # False: Too long
False

# Test character validity rules.
PS > "abcd,-." -match $test # True: Contains only valid chars
True
PS > "abcd+" -match $test # False: Contains invalid chars
False

# Test start rules.
PS > "1bcde" -match $test # True: Starts with a number
True
PS > ".abcd" -match $test # False: Starts with invalid character
False
PS > ",abcd" -match $test # False: Starts with invalid character
False
PS > "-abcd" -match $test # False: Starts with invalid character
False

答案 2 :(得分:0)

^([\d\w][\d\w.-]{4,29})$

制作:http://gskinner.com/RegExr/