Logo Wand.Tools

正規表示式產生器

智慧產生和解釋正規表示式,支援各種常見模式比對

如何使用正则表达式匹配 URL

✅ 常见 URL 格式

  • http://www.example.com
  • https://example.com/path?query=123
  • ftp://ftp.example.org/resource.txt
  • www.example.com
  • example.com

📌 正则表达式核心语法(适配 URL)

以下正则表达式可匹配绝大多数标准 URL:

\b((?:https?|ftp):\/\/)?(?:www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?:\/[^\s]*)?

🧪 Python 示例:提取文本中的 URL

import re

text = """
Visit our site at https://www.example.com or follow the docs at http://docs.example.org/page.
Also check ftp://ftp.example.com/file and plain www.test.com or example.net for more.
"""

pattern = r'\b((?:https?|ftp):\/\/)?(?:www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?:\/[^\s]*)?'
urls = re.findall(pattern, text)
print(urls)

🌐 JavaScript 示例:网页中提取所有链接

const text = `
  Check https://www.example.com, http://example.org, ftp://files.example.net,
  and also www.test.com or just example.co.
`;

const regex = /\b((?:https?|ftp):\/\/)?(?:www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?:\/[^\s]*)?/g;
const urls = text.match(regex);
console.log(urls);

☕ Java 示例:使用 Pattern 匹配 URL

import java.util.regex.*;
import java.util.*;

public class URLMatcher {
    public static void main(String[] args) {
        String text = "Visit https://example.com or ftp://ftp.example.org.";
        String regex = "\\b((?:https?|ftp):\\/\\/)?(?:www\\.)?[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}(?:\\/[^\\s]*)?";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

🔎 进阶优化:更强大的 URL 匹配正则

\b((?:https?|ftp):\/\/)?(?:www\.)?[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2,})(?::\d{1,5})?(?:\/[^\s]*)?

此正则支持:

  • 可选协议(http/https/ftp)
  • 可选 www
  • 顶级域名(.com/.org/.net/.io 等)
  • 可选端口号(:80, :443 等)
  • 可选路径和参数(/path?query)

🔍 实用场景

  • 提取网页 HTML 中的所有链接地址
  • 日志文件中的 URL 捕捉
  • 聊天记录、文档内容中的超链接提取
  • 自定义搜索引擎输入提取