Logo Wand.Tools

Regular Expression Generator

Intelligently generate and explain regular expressions, supporting various common pattern matching

How to use Regular Expressions to Match URLs

✅ Common URL Formats

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

📌 Core Regular Expression Syntax (for URLs)

The following regular expression can match most standard URLs:

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

🧪 Python Example: Extracting URLs from Text

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 Example: Extracting All Links from a Webpage

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 Example: Using Pattern to Match URLs

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());
        }
    }
}

🔎 Advanced Optimization: A More Powerful URL Matching Regex

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

This regex supports:

  • Optional protocol (http/https/ftp)
  • Optional www
  • Top-level domain (.com/.org/.net/.io, etc.)
  • Optional port number (:80, :443, etc.)
  • Optional path and parameters (/path?query)

🔍 Practical Scenarios

  • Extracting all link addresses from webpage HTML
  • Capturing URLs in log files
  • Extracting hyperlinks from chat history, document content
  • Extracting input for custom search engines