Regex for URL with port validation

前端 未结 1 2028
暗喜
暗喜 2021-01-21 06:28

I need to validate a url like those of web servers. Something like http://localhost:8080/xyz

How do we do that using regex. Sorry, new to regex.

1条回答
  •  走了就别回头了
    2021-01-21 06:50

    the relevant specs can be found in rfc 3986 and include regular syntax definitions for all possible url components. however, for your purposes these will probably be too general. a somewhat condensed expression matching only urls under the http(s) protocol would be

    http[s]?://(([[:alpha:][:digit:]-._~!$&'\(\)*+,;=]|%([0-9A-F]{2}))+|([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]))(:[0-9]+)?(/([[:alpha:][:digit:]-._~!$&'\(\)*+,;=]|%([0-9A-F]{2}))*)+(\?([[:alpha:][:digit:]-._~!$&'\(\)*+,;=/?]|%([0-9A-F]{2}))+)?(#([[:alpha:][:digit:]-._~!$&'\(\)*+,;=/?]|%([0-9A-F]{2}))+)?

    which can be simplified to

    http[s]?://(([^/:\.[:space:]]+(\.[^/:\.[:space:]]+)*)|([0-9](\.[0-9]{3})))(:[0-9]+)?((/[^?#[:space:]]+)(\?[^#[:space:]]+)?(\#.+)?)?

    in case you can be confident about the proper syntax of the url components.

    note that you might wish more restrictive patterns e.g. for full text search and to only allow for iana-registered top-level-domains.

    hope it helps,

    best regards, carsten

    0 讨论(0)
提交回复
热议问题