问题描述
我正在尝试验证将用作子域的用户输入字符串.规则如下:
I'm attempting to validate a string of user input that will be used as a subdomain. The rules are as follows:
- 长度介于 1 到 63 个字符之间(我从 Google Chrome 在子域中允许的字符数中取了 63,不确定它是否实际上是服务器指令.如果您对有效最大长度有更好的建议,我是有兴趣听)
- 可能包含 a-zA-Z0-9、连字符、下划线
- 不得以连字符或下划线开头或结尾
从下面的输入中,我添加了以下内容:4. 不应包含连续的连字符或下划线.
From input below, I've added the following:4. Should not contain consecutive hyphens or underscores.
示例:
a => valid
0 => valid
- => not valid
_ => not valid
a- => not valid
-a => not valid
a_ => not valid
_a => not valid
aa => valid
aaa => valid
a-a-a => valid
0-a => valid
a&a => not valid
a-_0 => not valid
a--a => not valid
aaa- => not valid
我的问题是我不确定如何使用 RegEx 指定字符串只能是一个字符,同时还指定它不能以连字符或下划线开头或结尾.
My issue is I'm not sure how to specify with a RegEx that the string is allowed to be only one character, while also specifying that it may not begin or end with a hyphen or underscore.
谢谢!
推荐答案
您可以在子域中使用下划线,但是您需要它们吗?在 trim
ming 你的输入之后,做一个简单的字符串长度检查,然后用这个测试:
You can have underscores in subdomains, but do you need them? After trim
ming your input, do a simple string length check, then test with this:
/^[a-z\d]+(-[a-z\d]+)*$/i
使用上述方法,您将不会获得连续的 -
字符,例如a-bbb-ccc
通过,a--d
失败.
With the above, you won't get consecutive -
characters, e.g. a-bbb-ccc
passes and a--d
fails.
/^[a-z\d]+([-_][a-z\d]+)*$/i
也允许不连续的下划线.
Will allow non-consecutive underscores as well.
更新:您会发现,在实践中,不允许使用下划线,并且所有子域都必须以字母开头.上面的解决方案不允许国际化子域(punycode).你最好用这个
Update: you'll find that, in practice, underscores are disallowed and all subdomains must start with a letter. The solution above does not allow internationalised subdomains (punycode). You're better of using this
/\A([a-z][a-z\d]*(-[a-z\d]+)*|xn--[\-a-z\d]+)\z/i
这篇关于Ruby 中有效子域的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!