如何在这个正则表达式中接受端口号?

huangapple go评论38阅读模式
英文:

How to accept port number in this regex?

问题

这是URL验证的正则表达式:

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

这部分代码可以保持不变。如果要修改以接受端口号,您可以尝试以下正则表达式:

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})(:[0-9]+)?([\/\w \.-]*)*\/?$/

这将允许匹配带有端口号的URL,例如:http://localhost:3000

英文:

This is url validation regex

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

This works Okay.
However if I type url with port number such as http://localhost:3000, it gives an error.

How can I change this expression to accept a port number as well?

答案1

得分: 3

https?:这部分匹配URL的协议部分。s是可选的,因此它匹配http和https。

:\/\/:这匹配协议中的冒号和两个正斜杠。

(?:w{1,3}\.)?:这匹配可选的www子域(如果存在)。(?: )创建一个非捕获组,{1,3}量词匹配1到3个"w"字母。

[^\s.]+:这匹配域名,由一个或多个不是空格或点的字符组成。

(?:\.[a-z]+)*:这匹配在域名之前可能存在的任何可选子域,以点分隔。(?: )创建另一个非捕获组,*量词匹配零个或多个该组的实例。[a-z]+匹配一个或多个小写字母。

(?::\d+)?:这匹配可能在域名之后出现的可选端口号,由冒号前缀。(?: )创建另一个非捕获组,?量词使其可选。:匹配冒号,\d+匹配一个或多个数字。

(?![^&lt;]*(?:&lt;\/\w+&gt;|\/?&gt;)):这是一个负向先行断言,确保URL不是HTML标签的一部分。它检查URL之前是否没有与模式(?:</\w+>|/?>)匹配的字符,该模式匹配任何闭合的HTML标签或空标签。

英文:

Please can try this one

https?:\/\/(?:w{1,3}\.)?[^\s.]+(?:\.[a-z]+)*(?::\d+)?(?![^&lt;]*(?:&lt;\/\w+&gt;|\/?&gt;))

https?: This part matches the protocol of the URL. The s is optional, so it matches both http and https.

:\/\/: This matches the colon and two forward slashes that are part of the protocol.

(?:w{1,3}\.)?: This matches the optional www subdomain, if it exists. The (?: ) creates a non-capturing group, and the {1,3} quantifier matches between 1 and 3 instances of the letter "w".

[^\s.]+: This matches the domain name, which consists of one or more characters that are not whitespace or a dot.

(?:\.[a-z]+)*: This matches any optional subdomains that come before the domain, separated by dots. The (?: ) creates another non-capturing group, and the * quantifier matches zero or more instances of this group. The [a-z]+ matches one or more lowercase letters.

(?::\d+)?: This matches an optional port number that might come after the domain, preceded by a colon. The (?: ) creates another non-capturing group, and the ? quantifier makes it optional. The : matches the colon, and \d+ matches one or more digits.

(?![^&lt;]*(?:&lt;\/\w+&gt;|\/?&gt;)): This is a negative lookahead that ensures that the URL is not part of an HTML tag. It checks if there are no characters before the URL that match the pattern (?:&lt;\/\w+&gt;|\/?&gt;), which matches any closing HTML tag or an empty tag.

huangapple
  • 本文由 发表于 2023年4月17日 13:04:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定