我正在寻找一个正则表达式来创建一个符合以下条件的字符串:
“徽章”字符串将需要在网站的网址中使用,任何有关此字符串是否正常的建议都将受到赞赏。
谢谢
答案 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})$