XML technologies / Regular expressions / Practical regex techniques / HTML examples / Matching a URL in practice
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
While working at Yahoo! Finance, I wrote programs to process incoming financial and stock-market news. Articles usually arrive as plain ASCII text, and my programs convert them to readable HTML. If you have visited "http://finance.yahoo.com" during the past ten years, you have seen how well I succeeded.
This is not always easy, since incoming text may have arbitrary formatting or none at all. It is much harder to identify hostnames and URLs in such text than to check their syntax once extracted. The preceding section hinted at this; here I show code actually used at Yahoo!
The program searches for several URL types: mailto, http, https and ftp. Finding ›http://‹ in text strongly suggests a genuine URL, so we use a relatively simple regex such as ˹http://[-\w]+(\.\w[-\w]*)+˼ to find the hostname. Since the text is English ASCII, we can safely use ˹-\w˼ instead of ˹[-a-z0-9]˼. ˹\w˼ also matches underscore and, on some systems, all Unicode characters, but that does not matter for these data.
Web addresses, however, often appear in abbreviated form without http:// or mailto:, for example:
...visit us at www.oreilly.com or mail to orders@oreilly.com.
These cases require more caution. At Yahoo!, I used an expression similar to the previous section’s, with a few differences:
(?i: [a-z0-9] (?:[-a-z0-9]*[a-z0-9])? \. )+ # Subdomains.
# Top-level-Domains -- wir verlangen hier Kleinbuchstaben.
(?-i: com\b
| edu\b | biz\b
| org\b | gov\b
| in(?:t|fo)\b # .int oder .info
| mil\b | net\b
| name\b | museum\b
| coop\b | aero\b
| [a-z][a-z]\b # Zweibuchstabige Ländercodes nach ISO.
)This regex uses ˹(?-i:...)˼ and ˹(?i:...)˼, so some parts match case-sensitively and others do not (see Comments and mode modifiers). We want mixed-case URLs such as ›www.OReilly.com‹ , but not stock symbols such as ›NT.TO‹, Nortel Networks’ symbol on the Toronto exchange; our financial data contain many such abbreviations. Officially, the RFC allows uppercase in the final hostname component, such as ›.com‹, but this is rare in practice, so we ignore it. We must balance recognizing every URL, avoiding stock symbols, and complexity. We could apply ˹(?-i:...)˼ only to two-letter ISO country codes, but entirely uppercase URLs are uncommon.
The following skeleton program finds URLs in text; insert the individual hostname subexpressions:
\b
# Protokollteil mit Hostname oder nur Hostname
(
# Protokoll-Präfix ftp://, http:// oder https://
(ftp|https?)://[-\w]+(\.\w[-\w]*)+
|
# Wenn ohne Präfix: ein spezifischerer Unterausdruck für den Hostnamen
Volle-Hostnamen-Regex
)
# Optionale Portnummer
( : \d+ )?
# Der Rest der URL ist fakultativ; wenn vorhanden, beginnt er mit einem Slash.
(
/ Pfad-Teil
)?We have not yet examined the path component, the part after the hostname, underlined in "http://www.oreilly.com/catalog/regex/". It is the hardest part to recognize; some guessing is needed for a practical regex. As seen under Extended introductory examples, text immediately following a URL could often legally be part of it.
In text such as
Lesen Sie seine Kommentare auf "http://www.oreilly.com/ask_tim/index.html". Er ...
, you can easily see that the dot after ›index.html‹ ends a sentence and is not part of the URL. However, the dot inside of ›index.html‹ does belong to the URL.
This is obvious to a human but much harder for a program; heuristics are required. In the example under Extended introductory examples, negative lookbehind prevented the URL from ending with punctuation. I developed Yahoo! Finance’s solution before negative lookbehind existed. It is more complicated than the method under Extended introductory examples but achieves the same result. The following listing shows it; it differs in several ways from the Example in Linking HTTP URLs; comparing them is worthwhile. In particular, the Java version of the same regex in the box Building a regex from variables in Java shows its structure clearly.
\b
# Protokollteil mit Hostname oder nur Hostname
(
# Protokoll-Präfix ftp://, http:// oder https://
(ftp|https?)://[-\w]+(\.\w[-\w]*)+
|
# Wenn ohne Präfix: ein spezifischerer Unterausdruck für den Hostnamen
(?i: [a-z0-9] (?:[-a-z0-9]*[a-z0-9])? \. )+ # Subdomains
# Top-level-Domains -- wir verlangen hier Kleinbuchstaben.
(?-i: com\b | edu\b
| biz\b | gov\b
| in(?:t|fo)\b # .int oder .info
| mil\b | net\b
| org\b | [a-z][a-z]\b # Zweibuchstabige Ländercodes nach ISO
)
)
# Optionale Portnummer
( : \d+ )?
# Der Rest der URL ist fakultativ; wenn vorhanden, beginnt er mit einem Slash.
(
/
# Für den Rest gehen wir heuristisch vor: Was in der Praxis funktioniert, ist »korrekt«.
[^!.,?;"fl<>()\[\]{}\s\x7F-\xFF]*
(?:
[!.,?]+ [^!.,?;"fl<>()\[\]{}\s\x7F-\xFF]+
)*
)?Building a regex from variables in Java
String SubDomain = "(?i:[a-z0-9]|[a-z0-9][-a-z0-9]*[a-z0-9])";
String TopDomains = "(?x-i:com\\b \n" +
" |edu\\b \n" +
" |biz\\b \n" +
" |in(?:t|fo)\\b \n" +
" |mil\\b \n" +
" |net\\b \n" +
" |org\\b \n" +
" |[a-z][a-z]\\b \n" + // Ländercodes
") \n";
String Hostname = "(?:" + SubDomain + "\\.)+" + TopDomains;
String NOT_IN = ";\"'<>()\\[\\]{}\\s\\x7F-\\xFF";
String NOT_END = "!.,?";
String ANYWHERE = "[^" + NOT_IN + NOT_END + "]";
String EMBEDDED = "[" + NOT_END + "]";
String UrlPath = "/"+ANYWHERE + "*("+EMBEDDED+"+"+ANYWHERE+"+)*";
String Url =
"(?x: \n"+
" \\b \n"+
" ## Hostname-Teil erkennen \n"+
" ( \n"+
" (?: ftp | http s? ): // [-\\w]+(\\.\\w[-\\w]*)+ \n"+
" | \n"+
" " + Hostname + " \n"+
" ) \n"+
" # Optionale Portnummer zulassen \n"+
" (?: :\\d+ )? \n"+
" \n"+
" # Rest der URL ist optional und beginnt mit / \n"+
" (?: " + UrlPath + ")? \n"+
")";
// String-Darstellung der Regex in ein Regex-Objekt umwandeln.
Pattern UrlRegex = Pattern.compile(Url);
// Jetzt können wir die Regex auf Textdateien anwenden ...
.
.
.In reality, I would hardly write such a huge monster regex. Instead, I would build a small collection or library of regular expressions and combine them into a larger one. We saw a simple example using the variable $HostnameRegex under A regex collection and in the Java version of the same program in the box above.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln