XML technologies / Regular expressions / Introduction to regular expressions / Expanding the foundations
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
I hope the examples and explanations so far have provided a solid foundation for understanding regular expressions. But we have not yet explored anything in real depth. There is much more to learn!
Linguistic diversion
I mentioned several features supported by almost every version of egrep. But there are more, and not every version supports all of them.
Unfortunately regex languages resemble natural languages: they have many dialects, not to mention accents and differences in emphasis. Almost every new regex tool seems to introduce its own improvements. The field is evolving, of course, but over the years a wide range of dialects has developed. We will encounter quite a few.
The purpose of a regular expression
Overall, a regex either matches some text—a line in egrep—or it does not. When constructing one, keep this tension between matching and not matching in mind.
egrep does not care where on a line a pattern matches: if it occurs anywhere, the line is printed. Other tools may care a great deal. Suppose the text is
...Postleitzahl 50670. Bitte 4,50 Euro in Briefmarken für Rückporto...
and you only want lines containing digits (˹[0-9]+˼). It does not matter which number matches. But if you want to process the matched numbers—write them to a file, add something, and so on—it is important which number matches. Buying stamps for 50 670 euros is rather different from buying them for 4.50 euros.
More examples
As with any language, practice is very important. So here are examples matching fre⟦U+0002⟧quently encountered constructs.
Matching patterns is half the job of constructing regexes. Avoiding unwanted matches is the other half. Both matter, but for now I will focus on the first. We will not pursue every detail, since the main purpose is practice.
Variable names
Many programming languages have identifiers for variables and similar items, made of alphanumeric characters and underscore but not starting with a digit: ˹[a-zA-Z_][a-zA-Z_0-9]*˼. The first class matches the initial character; the second, with star, matches the rest. If identifier length is limited, often to 32, and the tool supports ˹{min, max}˼ notation, star can be replaced with ˹{0,31}˼, the interval construct briefly introduced in Explicit minimum and maximum: Intervals.
A quoted string
A simple solution might be ˹"[^"]*"˼.
The opening and closing quotes must appear literally in the text. Anything can appear between them except another quote! So we use the negated class ˹[^"]˼ and star to allow any number of non-quote characters.
A more sophisticated and complicated defi⟦U+0002⟧nition allows quotes within the string, escaped with a preceding backslash, for example "^●oder●\"Hütchen\"●oder●Zirkumflex". Later chapters return to this harder interpretation when examining exactly how matching works.
Dollars and cents
Here is an initial regex for monetary amounts with fractional parts, using dollars and cents: ˹\$[0-9]+(\.[0-9][0-9])?˼.
Looking from the outside inward, the regex has three parts: ˹\$˼ and ˹...+˼ and ˹(...)?˼. Loosely: a dollar sign, one or more things, then perhaps another thing. The first thing is a digit—several make a number—and the other is a decimal point followed by two digits.
This is naive for several reasons. First, monetary amounts sometimes group digits in threes, with commas in the USA, periods in Germany, or apostrophes in Switzerland: $1,000. With egrep, we generally care only whether a dollar amount appears on the line; cents are irrelevant, since the line is printed anyway. For egrep it does not matter how much of the text matches, only whether the regex matches at all or not.
If we wanted lines containing nothing but this amount, we would wrap the regex in ˹^...$˼. Then the optional cents matter: they may or may not occur between the whole dollar amount and the line end.
Our regex misses one kind of dollar amount: ›$.49‹. Replacing plus with star is tempting, but fails. Why? We will leave that open until Regex techniques in practice, where we tackle a similar problem.
An HTTP/HTML URL
The general URL format is surprisingly complicated, as is the corresponding regex. Lowering our expectations to the most com⟦U+0002⟧mon URL forms simplifies matters. For example, we may search our email archive for a vaguely remembered URL; strict correctness matters less than printing many URLs. The desired ones ⟦U+0002⟧can be spotted by quickly reading the output of egrep.
Ordinary HTTP/HTML URLs generally have this form:
http://servername/pfad.html
The ending .htm is also com⟦U+0002⟧mon.
The exact hostname rules, for the servername here, such as www.yahoo.com, are not simple either. For now, ˹[a-z0-9_.]+˼ is enough for what follows ›http://‹. The pfad can vary even more; we will use ˹[a-z0-9_:@&?=+,.!/~*%$]*˼. Notice both character classes start with a literal hyphen; otherwise it would be interpreted as a range marker.
Putting it together, our first attempt is:
% egrep -i ⟦U+001F⟧'\<http://[-a-z0-9_.]+/[-a-z0-9_:@&?="+,.!/~*%$]*\.html?\>⟦U+001F⟧' dateien ...
Again we are generous, allowing far more than is valid. The expression would match »http://..../foo.html«, which certainly is not a valid URL. Is that a problem? It depends on the goal. Searching email can tolerate a few false matches. Even something simpler such as
% egrep -i ⟦U+001F⟧'\<http://[^ ]*\.html?\>'⟦U+001F⟧ dateien ...
could work well. Know what data to expect. As we learn regex construction, balancing complexity against completeness becomes increasingly important. The next chapter explores this example more fully.
An HTML tag
A tool such as egrep is not particularly useful for finding lines with HTML tags. Still, regexes matching HTML tags are often needed, especially in the programming languages discussed later.
Simple cases such as <TITLE> or <HR> suggest the simple regex ˹<.*>˼. Almost everyone thinks of this, but it is wrong. In words, ˹<.*>˼ means “find <, followed by anything, followed by >.” This makes it clear that it can match several tags at once, as in the underlined part of ›ein <I>kleines</I> Beispiel‹.
This may surprise you, but we are still in the first chapter and understand regexes only superfi⟦U+0003⟧cially. The example shows that regexes are not particularly hard, but become hard if you do not understand what happens. Later chapters examine every detail so we can understand and solve this problem.
American times such as “9:17 am” and “12:30 pm”
Matching American times can be handled loosely or strictly. Translator’s note: Americans have trouble imagining a 24-hour day. They generally prefer twelve-hour notation, followed by am, sometimes a.m. or a, ante meridiem, before noon, or pm, post meridiem, after noon. Zero-hour times such as 0.13 or 12.59 are almost incomprehensible; Americans write “12:13 pm” and “12:59 am” instead, although 12.59 is certainly not before noon. End of translator’s note. A regex such as
˹
[0-9]?[0-9]:[0-9][0-9]●(am|pm)˼
matches both 9:17●am and 12:30●pm, but also allows nonsense such as 99:99●pm.
For two-digit hours, the first digit must be 1. But ˹1?[0-9]˼ still allows hours of 19, and even 0, so splitting hours into two alternatives is wiser: ˹1[012]˼ for two-digit hours and ˹[1-9]˼ for one-digit hours, giving ˹(1[012]|[1-9])˼.
Minutes are simpler: the first digit must match ˹[0-5]˼, and the second can remain ˹[0-9]˼. Combining everything gives ˹(1[012]|[1-9]):[0-5][0-9]●(am|pm)˼.
How would you extend this to the usual 24-hour clock, with hours from 0 to 23? As an extra challenge, allow leading-zero hours such as 09:59. The answer is in Solution 4. Please ⟦U+0002⟧find your own solution before following the link.
Regex terminology
Regex
Repeatedly writing the full term “regular expression” becomes tiring. I normally use “regex”, short for “regular expression”. I sometimes speak of translating an idea into Regexese or even regexi⟦U+0002⟧fying it. Note: elsewhere you will see the ugly “Regexp.” I can barely pronounce that; people with a lisp probably have less trouble. I use “regex engine”, or simply engine, for the program doing the actual pattern matching.
Pattern matching
When, during pattern matching, I speak of a match , I mean the engine found matching text. More precisely, ˹i˼ does not match the string ding, but only the i in the text ding. This is for completeness; the distinction rarely causes confusion.
Metacharacters
Whether something is a metacharacter or metasequence, terms I use interchangeably, depends on its position. For example, ˹*˼ is a metacharacter only outside classes and when not escaped by a preceding backslash. An escape is a backslash-protected character—usually. In ˹\*˼, backslash and star form an escape, but not in ˹\\*˼, where the first backslash escapes the second, even though both stars have an escape character in front of them.
Different dialects may treat a character as special in one case and ordinary in another. Features and dialects gives details.
Dialects
Tools use regexes for very different purposes and support very different metacharacters. Consider word boundaries again: some versions of egrep use the \<...\> notation. Others do not distinguish word start and end, using one metacharacter, ˹\b˼, for a word boundary. Others know all three, and some know none.
I use dialect to mean the sum of these small implementation differences, by analogy with natural languages. It is not just whether particular metacharacters are supported: even two tools recognizing ˹\<...\>˼ may disagree on what counts as a word. That matters when a tool is actually used rather than merely evaluated.
Dialect does not mean tool or program. Two people can speak the same dialect; different tools can share a regex dialect. Conversely, tools with the same name and purpose may have subtly different microdialects, sometimes not so subtly. The many egrep implementations support almost as many regex dialects.
In the late 1990s, the language Perl became popular with its rich regex dialect. Other languages copied it, some openly calling themselves Perl-compatible. These include PHP, Python, many regex packages for Java, Microsoft’s .NET, Tcl, and many C libraries. Yet small, important differences remain. Perl’s regexes also keep evolving, sometimes borrowing ideas from imitators. The landscape expands and changes, not always becoming simpler.
Subexpression
A subexpression is simply part of a larger regex, usually more specifi⟦U+0002⟧cally a parenthesized part or a branch of an alternation. For example, ˹Subject|Date˼ is a subexpression of ˹^(Subject|Date):●˼. Within it, the alternatives ˹Subject˼ and ˹Date˼ are subexpressions too.
But something like ˹1-6˼ is not a subexpression of ˹H[1-6]l*˼, because ˹1-6˼ is part of an indivisible unit, a character class. Conversely, ˹H˼, ˹[1-6]˼, and ˹●*˼ are subexpressions of the original.
Quantifiers—star, plus, question mark—always apply to the immediately preceding subexpression. That is why the + in ˹vertip+t˼ controls only ˹p˼, not ˹vertip˼ or ˹ip˼. A preceding parenthesized subexpression, of course, is quantified as a whole, however complex it is.
Character
In computing, a character can mean very different things depending on context. Interpreting a byte as a character is largely a matter of perspective; the byte’s numeric value, however, stays the same in any context. Which character it represents depends on the character set. Two bytes with decimal values 64 and 53 represent @ and 5 in ASCII, but something entirely different in EBCDIC: a space and a control character.
In one of the Japanese character sets, the same two bytes form a single character, 正. EUC-JP uses two entirely different bytes for 正. Interpreted with the Latin-1 character set (ISO-8859-1), these form the two characters Àμ, or the single Korean character 삵 in the Unicode character set. Note: the standard reference on multibyte sets is CJKV Information Processing by Ken Lunde, also published by O’Reilly. CJKV stands for Chinese, Japanese, Korean and Vietnamese, all languages requiring multibyte character sets. Ken and Adobe supplied the special fonts for this book. The crucial point is that perspective determines how many bytes constitute a character, forming an encoding . When comparing characters, ensure your perspective agrees with your tool or language.
Until recently, almost all regex tools treated data as collections of 8-bit bytes, paying little attention to encoding. Increas⟦U+0002⟧ingly, however, tools use some variant of Unicode internally. For an introduction to Unicode, see Features and dialects. Users of such systems can normally dis⟦U+0002⟧pense with these concerns if regex support is correctly implemented. If only that “if” were guaranteed! That is why Features and dialects examines this more closely.
Improving the status quo
Regexes are not especially difficult if studied seriously. But among users of regex tools you will often ⟦U+0002⟧find people who understand a little but lack the confidence to tackle complex tasks or use less fre⟦U+0002⟧quently used tools.
Traditional regex documentation often gives only brief descriptions of one or two metacharacters, then a table of the rest. It shows expressions such as ˹a*((ab)*|b*)˼ with meaningless sample data such as ›a●xxx●ce●xxxxxx●ci●xxx●d‹, unrelated to practice. Subtle but important issues are usually omitted, or a dialect is declared identical to another familiar tool’s without explaining the differences almost inevi⟦U+0002⟧tably present. This needs to change.
I do not claim this introductory chapter fills the gap: it only lays the foundation for the rest of the book. Ambitious as it sounds, I hope the whole book does fill it. The first edition received many encouraging responses, and I have worked to improve this second edition in both quantity and quality.
Perhaps precisely because traditional documentation is poor, I feel ob⟦U+0003⟧liged to explain things in detail. I want you to exploit the full potential of regexes and really, really understand them.
This is both good and bad.
Good, because you learn to think in regexes. You will recognize quirks and differences between dialects and express yourself even in a dull, incomplete dialect. You will understand why one regex is more effi⟦U+0002⟧cient than another, weigh effi⟦U+0002⟧ciency against complexity, and compare results. Facing a complex expression, you can follow how the tool processes it and analyze it the same way. In short, you will easily harness the full power of regexes.
Unfortunately this takes considerable learning effort in three areas:
How regexes are used
Most tools use regexes in more extensive ways than egrep did in our examples. Before details, we need to see how and where they are used. That is the subject of Extended introductory examples.
Regex features
Choosing the right tool for a problem often saves much time, so this book is not confined to one. Different tools, and even versions, have different features and metacharacters. We need an overview before using them; that is provided in Features and dialects.
How regexes really work
Learning from useful, often complex regexes requires understanding how tools execute them. Metacharacter evaluation order matters. Different implementations may do different things with the same expression. We tackle this substantial subject in How regex engines work and Regex techniques in practice.
This last part is the most important and hardest to present. It can be dry, requiring persistence before the exciting practical problem-solving begins. Yet understanding the engine is the key to truly understanding regexes.
You might argue that driving requires no knowledge of how a car works. True, but driving is a poor analogy. My goal is solving problems with regexes; building a car is a better comparison, and that probably does require knowing how it works.
Extended introductory examples is like a few more driving lessons. Features and dialects tells a little automotive history and discusses regex bodywork, paint, and main⟦U+0003⟧tenance, while How regex engines work examines the engine. Regex techniques in practice gives further examples; The art of writing regular expressions discusses engine tuning. Later chapters focus on particular makes and models. Especially in How regex engines work, Regex techniques in practice and The art of writing regular expressions we will spend time under the car, so work clothes and cleaning rags may be appropriate.
Summary
The next table summarizes the egrep metacharacters examined in this chapter.
Also remember these points:
Not every tool named egrep is the same. Metacharacters and meanings may differ; consult the local documentation.
Parentheses serve three purposes: limiting alternation scope, grouping, and remembering submatches.
Character classes are special: their metacharacter rules are entirely different.
Alternations and character classes are fundamentally different; only in exceptionally simple situations can their effect be the same.
Table: Summary of egrep metacharacters.
Metacharacter | Description | Matches |
Constructs matching single characters | ||
| Dot | Any character |
| Character class | One character from the list |
| Negated character class | Any character not in the list |
| Escape | If character is special, or the backslash combination does not create another metacharacter: the literal character |
Counting constructs: Quantifiers | ||
| Question mark | Allowed once, but optional |
| Star | Any number allowed, including zero |
| Plus | At least one, more allowed |
| Explicit intervala | min required; up to and including max allowed |
Constructs matching positions | ||
| Circum⟦U+0003⟧flex | Matches the start of a line |
| Dollar | Matches the end of a line |
| Word boundarya | Matches the start-of-word position |
| Word boundarya | Matches the end-of-word position |
Other | ||
| Alternation | Matches at least one alternative |
| Parentheses | Limit alternation scope, group for subsequent quantifiers, and remember text for backreferences |
| Backreferencesa | Matches text from the first, second, and subsequent parenthesis pairs |
a is not supported by every egrep version | ||
A negated class still needs a character to match: it remains a positive assertion. The list is negated, so the matching character must not appear in the list.
The
-ioption treats uppercase and lowercase as identical.There are three types of escape, characters preceded by a backslash:
Combining ˹
\˼ with a metacharacter creates a metasequence producing the original literal; for example, ˹\*˼ yields a literal star.Combining ˹
\˼ with certain ordinary characters creates a metacharacter whose meaning depends on the tool; for example, ˹\<˼ often means start of word.Combining ˹
\˼ with another character yields that character itself: the backslash is ignored.
Again, inside classes a backslash is ordinary in most egrep versions and does not introduce an escape.
Constructs quanti⟦U+0002⟧fied with question mark or star need no character to satisfy the assertion. They always match, even if they match no characters.
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