Logo Wand.Tools

Regular Expression Generator

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

Sådan bruger du regulære udtryk til at matche URL'er

✅ Almindelige URL-formater

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

📌 Kerne syntaks for regulære udtryk (til URL’er)

Følgende regulære udtryk kan matche de fleste standard-URL’er:

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

🧪 Python-eksempel: Udtrækning af URL’er fra tekst

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-eksempel: Udtrækning af alle links fra en webside

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-eksempel: Brug af Pattern til at matche URL’er

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

🔎 Avanceret optimering: Et mere kraftfuldt regulært udtryk til URL-matching

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

Dette regulære udtryk understøtter:

  • Valgfri protokol (http/https/ftp)
  • Valgfri www
  • Topdomæne (.com/.org/.net/.io osv.)
  • Valgfrit portnummer (:80, :443 osv.)
  • Valgfri sti og parametre (/path?query)

🔍 Praktiske scenarier

  • Udtrækning af alle linkadresser fra webside-HTML
  • Indfangning af URL’er i logfiler
  • Udtrækning af hyperlinks fra chathistorik, dokumentindhold
  • Udtrækning af input til brugerdefinerede søgemaskiner