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

用于类似facebook的个人资料徽章的Javascript正则表达式,javascript,regex,Javascript,Regex,我正在寻找一个正则表达式来创建具有以下条件的字符串: 可以是可变长度(最多30个字符) 只能有字母数字(a-z,a-z)和数字字符(0-9) 字符串中的任何位置都只能有这些特殊字符“-”、“” 只能以字母数字或数字开头,不能以特殊字符开头 必须至少包含5个字符 “徽章”字符串将需要在网站的url中使用,任何关于该字符串是否正确的建议都将不胜感激 谢谢^\w[\w-,\.]{4}[\w-,\.]{0,25}$ 这意味着: 匹配以字母数字开头的字符串,然后匹配4个有效字符, 然后最多再添加25个

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

  • 可以是可变长度(最多30个字符)
  • 只能有字母数字(a-z,a-z)和数字字符(0-9)
  • 字符串中的任何位置都只能有这些特殊字符“-”、“”
  • 只能以字母数字或数字开头,不能以特殊字符开头
  • 必须至少包含5个字符
“徽章”字符串将需要在网站的url中使用,任何关于该字符串是否正确的建议都将不胜感激


谢谢

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

使用:

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

哦,最少5个字符!刚刚意识到我的不太正确<代码>\w允许使用下划线。感谢大家的快速响应。我会测试每一个答案并报告,因为它们看起来都不一样。RegEx不是我的强项,希望我能更多地理解它们!感谢您澄清这一点,是的,我的意思是我从输入中获取了一个javascript变量,并希望对其进行验证。现在测试…+1我认为这是唯一正确的答案-我和da_b0uncer都允许错误的下划线。
   /^                  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