XML technologies / Regular expressions / Practical regex techniques / A few short examples / Working with filenames
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Filenames provide many good regex examples, whether Unix paths such as /usr/local/bin/perl or Windows filenames such as \Program Files\Yahoo!\Messenger. Experimenting is more fun than reading, so I embed the expressions in examples using Perl, PHP (the preg functions), Java, and VB.NET. Skip listings in languages that do not interest you: the regexes are what matter here.
Removing the directory from a pathname
First, remove a path's directory, leaving just the filename. For example, turn /usr/local/bin/gcc into gcc .
Formulating a problem to suggest its solution often helps. Here, remove everything through the last slash (backslash on Windows). With no slash, do nothing. I have repeatedly warned against careless use of ˹.*˼, but here its greediness is precisely what we need. In the regex ˹^.*/˼, ˹.*˼ initially consumes the whole line, then the regex engine backtracks to the last slash (backtracking) and finds an overall match.
The table shows how our four languages ensure that a path in f has no leading directory components:
Programming language | Code |
|---|---|
Perl |
|
PHP |
|
|
|
VB.NET |
|
The regex (or string interpreted as one) is underlined; matching-related elements are bold.
Windows paths use backslashes rather than slashes, giving ˹^.*\\˼. The engine requires a doubled backslash, but the middle two examples show that some languages require even more:
Programming language | Code |
|---|---|
Perl |
|
PHP |
|
|
|
VB.NET |
|
The differences between languages and Unix/Windows are striking, especially Java's quadrupled backslash (see Strings as regular expressions).
What if the regex fails? If the pathname in f contains no slash, substitution does not run and the string stays unchanged, exactly as intended.
To assess efficiency, examine an NFA engine. Suppose we omit the initial caret and search a string without slashes. Starting at the beginning, ˹.*˼ runs to the end, then gives back each character seeking a slash. Eventually backtracking reaches the starting point without a match. The engine decides there is no match from the beginning of the string. But the search is not over.
The transmission advances to the next character and restarts the engine. In theory, this repeats at every position. Filenames are usually short, but similar long subjects cause many backtracks. (A DFA has no such problem.)
In practice, a good transmission knows that a regex beginning with ˹.*˼ cannot match if it already failed at the start. It skips further positions and gives up (see Implicit anchoring optimization). Still, explicitly including the anchor is wiser.
Extracting filenames from a pathname
Alternatively, find the last component, the filename, and save it in another variable: everything at the end that is not a slash. ˹[^/]*$˼. Here the anchor is essential, not just an optimization. In Perl:
$Pfad =~ m{([^/]*)$}; # Variable $Pfad mit Regex testen
$DateiName = $1; # gefundenen Text abspeichernNotice that I do not check for success, because I know the regex always matches. Its only mandatory requirement is to end at the string's end, and even an empty string has an end. When I then use $1 to save the capture, I know something matched, even an empty string if the pathname ends in a slash.
Another efficiency note: for an NFA, an expression such as ˹[^\/]*$˼ is very inefficient. Following its steps reveals many backtracks. Even a short example like ›/usr/local/bin/perl‹ requires over 40 backtracks. Consider an attempt starting at ...▵local/.... ˹[^/]*˼ matches through the second l, then ˹$˼ fails against the slash, and a saved state must be retrieved for each character l, a, c, o, l. Most of this repeats on the next attempt starting at ...l▵ocal/..., then again at ...lo▵cal/..., and so on.
Here this is harmless: filenames are short and 40 backtracks are few; 40 million would be a problem. Keep it in mind for much longer subjects.
Although this is a regex book, regexes are not always the answer. Most languages have specialized pathname routines. For illustration, however, let us go further.
Extracting both directory and filename
Next, split a complete path into directory and filename. Many approaches depend on the requirements. One might try ˹^(.*)/(.*)$˼, using $1 and $2 to access the parts. The regex looks balanced, and greediness ensures that no slash reaches $2. The first ˹.*˼ leaves anything only because the slash forces backtracking. The second ˹.*˼ gets exactly what the first gave back. Thus the directory is in $1 and the filename, or last component, in $2.
We trust the first, greedy ˹(.*)/˼ to ensure that the second ˹(.*)˼ captures no slash. We understand greediness and can do this, but I prefer explicitly excluding slashes from the filename with ˹[^/]*˼: ˹^(.*)/([^/]*)$˼. This is also more self-explanatory.
This regex requires at least one slash. Applied to something like datei.txt , it fails. That may be intended, if the program handles it:
if ( $Pfad =~ m!^(.*)/([^/]*)$! ) {
# Treffer -- $1 und $2 sind gültig.
$Verzeichnis = $1;
$DateiName = $2;
} else {
# Kein Treffer, also enthält der Pfadname kein /.
$Verzeichnis = "."; # "datei.txt" wird zu "./datei.txt" ("." ist das Arbeitsverzeichnis).
$DateiName = $Pfad;
}
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