如何使用正则表达式来解析通用的复杂 URL?

Psy*_*hoX 1 javascript regex

如何使用正则表达式来解析通用的复杂 URL?

我想从 URL 字符串中获取信息,包括协议、主机名和路径。

Psy*_*hoX 5

使用正则表达式解析 URL

您可以使用正则表达式解析 URL/URI。

高级 URL 示例如下:

http://login:password@www.example.org:80/demo/example.cgi?lang=de&foo=bar&empty#position
Run Code Online (Sandbox Code Playgroud)

用于解析高级 URL 的 RegExr 类似于:

([^ :]*):\/\/(?:([^:]*):([^@]*)@|)([^/:]{1,}):?(\d*)?(\/[^? ]*)\??((?:[^=&# ]*=?[^&# ]*&?)*)#?([^ ]*)?
Run Code Online (Sandbox Code Playgroud)

是的,太疯狂了。但是,您可以从中获取以下字段(组):

#1 Protocol, #2 Login, #3 Password, #4 Host name, #5 Port, #6 Path, #7 Query, #8 Fragment
Run Code Online (Sandbox Code Playgroud)

假设您有一些 URL 并且只想知道主机名:

http://login:password@www.example.org:80/demo/example.cgi?lang=de&foo=bar&empty#position
Run Code Online (Sandbox Code Playgroud)

我还创建了一个很好的表,您可以在其中找到 URL 字符串的每个条目(在第 1 组)的 RegExpr:

| URL entry name    | Example               | Regular Expression              |
| ----------------- | --------------------- | ------------------------------- |
| Protocol          | http                  | ([^ :]*):\/\/                   |
| Login             | admin                 | \/\/([^:]*):[^@]*(?=@)          |
| Password          | 12345                 | \/\/[^:]*:([^@]*)(?=@)          |
| Host name         | www.example.org       | (?:@|\/\/)([^/:]{1,})           |
| Domain parts      | www, example, org     | (?:@|\/\/|\.)([^./:]*)(?=[./:]) |
| Port              | 80                    | :(\d*)\/[^/]                    |
| Path              | /demo/example.cgi     | \/\/([^/][^? ]*)\??             |
| File name         | example.cgi           | ([^?/]*(?!\/))\?                |
| Query string      | lang=de&foo=bar&empty | \?((?:[^=&# ]*=?[^&# ]*&?)*)    |
| Fragment/position | position              | #([^ ]*)                        |
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用([^=&# ]*)=?([^&# ]*)&?并迭代匹配来解析查询字符串:

([^ :]*):\/\/(?:([^:]*):([^@]*)@|)([^/:]{1,}):?(\d*)?(\/[^? ]*)\??((?:[^=&# ]*=?[^&# ]*&?)*)#?([^ ]*)?
Run Code Online (Sandbox Code Playgroud)

您可以在http://regexr.com/上轻松测试您的 RegExpr 。