0

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

  • 可以是可变长度(最多 30 个字符)
  • 只能包含字母数字 (az,AZ) 和数字字符 (0-9)
  • 只能有这些特殊字符“-”,“。” 字符串中的任何位置
  • 必须仅以字母数字或数字开头,不能以特殊字符开头
  • 必须至少为 5 个字符

“徽章”字符串将需要在网站的 url 中使用,任何关于此字符串是否可以的建议将不胜感激。

谢谢

4

3 回答 3

1

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
于 2012-05-18T10:04:17.343 回答
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
于 2012-05-18T10:02:34.427 回答
0
^([\d\w][\d\w.-]{4,29})$

使用: http: //gskinner.com/RegExr/

于 2012-05-18T10:03:01.733 回答