正确匹配 IDN URL
我需要帮助构建一个可以正确匹配自由文本中的 URL 的正则表达式.
- 方案
- 以下之一:ftp、http、https(ftps 是协议吗?)莉>
- scheme
- One of the following: ftp, http, https (is ftps a protocol?)
- 支持www 和子域(支持 IDN)
- TLD 的基本过滤(我认为
[a-zA-Z]{2,6}
就足够了)
- support for www and sub-domain(s) (with support for IDNs)
- basic filtering of TLDs (
[a-zA-Z]{2,6}
is enough I think)
以下是关于子域的信息:
Here is what I could find out about sub-domains:
子域"表示相对依赖,而不是绝对依赖:例如,wikipedia.org 包括一个org 域的子域,以及en.wikipedia.org 包含一个子域wikipedia.org 域的名称.在理论上,这个细分可以下降到 127 层深,每个 DNS 标签最多可以包含 63 个字符,如只要整个域名不总长度超过 255字符.
A "subdomain" expresses relative dependence, not absolute dependence: for example, wikipedia.org comprises a subdomain of the org domain, and en.wikipedia.org comprises a subdomain of the domain wikipedia.org. In theory, this subdivision can go down to 127 levels deep, and each DNS label can contain up to 63 characters, as long as the whole domain name does not exceed a total length of 255 characters.
关于域名本身,我找不到任何可靠的来源,但我认为非 IDN 的正则表达式(我不确定如何编写 IDN 兼容版本)类似于:
Regarding the domain name itself I couldn't find any reliable source but I think the regular expression for non-IDNs (I'm not sure how to write a IDN compatible version) is something like:
[0-9a-zA-Z][0-9a-zA-Z-]{2,62}
有人能帮我解决这个正则表达式或给我指明一个好的方向吗?
推荐答案
因 Daring Fireball 成名的 John Gruber,拥有 最近的一篇文章 详细介绍了他对一个良好的 URL 识别正则表达式字符串的追求.他想出了这个:
John Gruber, of Daring Fireball fame, had a post recently that detailed his quest for a good URL-recognizing regex string. What he came up with was this:
<代码>(([w-]+://?|www[.])[^s()<>]+(?:([wd]+)|([^[:punct:]s]|/)))
这显然也适用于包含 Unicode 的 URL.您需要对其稍作修改以获得您正在寻找的其余内容——方案、用户名、密码等. Alan Storm 写了一篇解释 Gruber 的正则表达式模式的文章,我绝对需要它(正则表达式是如此写一次,没有线索,如何再读一次!).
Which apparently does OK with Unicode-containing URLs, as well. You'd need to do the slight modification to it to get the rest of what you're looking for -- the scheme, username, password, etc. Alan Storm wrote a piece explaining Gruber's regex pattern, which I definitely needed (regex is so write-once-have-no-clue-how-to-read-ever-again!).
相关文章