XML technologies / Regular expressions / Practical regex techniques / A few short examples / Matching an IP address
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Another example, now examined in much greater detail, is matching IP (Internet Protocol) addresses: four numbers separated by periods, such as 1.2.3.4. These numbers often have leading zeros, as in 001.002.003.004. A simple test would be ˹[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*˼, but it is so imprecise that it even matches ›und dann.....?‹. The regex does not require a single digit: it requires only three periods, with digits between them or none.
First, replace stars with plus signs, since each number must contain at least one digit. To exclude anything except the address, enclose the expression in ˹^...$˼. This gives:
˹^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$˼
Replacing the character class ˹[0-9]˼ with the shorthand ˹\d˼ gives a more readable form (note: or not, depending on your habits; in complex regexes I find ˹\d˼ easier to read than ˹[0-9]˼, but on some systems they are not exactly equivalent. On Unicode systems, ˹\d˼ can also match non-ASCII digits; see Character-class shorthands). ˹^\d+\.\d+\.\d+\.\d+$˼, but it still allows nonaddresses such as ›1234.5678.9101112.131415‹ (each number must be from 0 to 255). Requiring three digits with ˹^\d\d\d\.\d\d\d\.\d\d\d\.\d\d\d$˼ goes too far, since one- and two-digit numbers, as in 1.2.3.4, would fail. If the dialect supports {min,max} notation, use ˹^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$˼; otherwise use ˹\d\d?\d?˼ or ˹\d(\d\d?)?˼ for each component. Each regex allows one to three digits in a different way.
Depending on your needs, one of these precision levels may suffice. For stricter validation, remember that ˹\d\d\d˼ also matches 999 , far above 255 and invalid as an address component.
There are several ways to restrict numbers to 0–255. A foolish approach is ˹0|1|2|3|...253|254|255˼, which even misses leading zeros, requiring ˹0|00|000|1|01|001|...˼. That is ridiculous. For a DFA it is merely long, but as efficient as any equivalent expression. For an NFA, however, all those alternatives are inefficient.
A practical approach considers which digits are allowed at each position. One- and two-digit numbers are always within range, so use ˹\d|\d\d˼. Three-digit numbers beginning with 0 or 1 are also safe: they cover 000–199. Add ˹[01]\d\d˼ to obtain ˹\d|\d\d|[01]\d\d˼. This may recall the time example from Introduction to regular expressions (see Solution 4) or the calendar-date example from How regex engines work (see the box Ways to divide calendar dates).
If a three-digit number begins with 2, it must stay below 255, so the second digit may be less than 5 . If the second digit is 5, the third must be less than 6. Express this with ˹2[0-4]\d|25[0-5]˼.
Initially confusing perhaps, but the approach is logical. The result is ˹\d|\d\d|[01]\d\d|2[0-4]\d|25[0-5]˼. Merge the first three alternatives to get ˹[01]?\d\d?|2[0-4]\d|25[0-5]˼. This is more efficient for an NFA, since every failed alternative triggers backtracking. Using ˹\d\d?˼ instead of ˹\d?\d˼ in the first alternative saves an NFA a little work when no digit occurs. Analyze it yourself; a small test should show the difference. More optimizations are possible, but I defer them to The art of writing regular expressions.
We now have a subexpression matching a number from 0 to 255. Parenthesize it and replace each ˹\d{1,3}˼ in the earlier regex, producing (split over two lines):
˹^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\. ([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$˼
Quite a mouthful! Was it worth the effort? That depends on your requirements. It allows only syntactically correct addresses, yet some remain semantically invalid, such as 0.0.0.0 (not all bytes may be zero). Lookahead (see Lookahead; lookbehind) could exclude even this case by adding, after ˹^˼, the construct ˹(?!0+\.0+\.0+\.0+$)˼. But decide where greater specificity stops being worth its cost. Sometimes it is easier to move work outside the regex. Use the simpler, clearer ˹^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$˼ and capture each component, making the numbers available in $1, $2, $3 and $4. Then use other language facilities to check their ranges.
Understanding the context
The two anchors above are important, and understanding why matters. Without them, the expression would match ip=72123.3.21.993; a traditional NFA would even match ip=123.3.21.223.
In this second case, it does not even match the entire final number 223 , although it could. It is allowed, but nothing in the expression, such as a final period or anchor, requires three digits. The final group's first alternative, ˹[01]?\d\d?˼, matches two digits and reaches the regex's end. As in the calendar-date problem in Ways to divide calendar dates, reorder the alternatives to obtain the desired effect. Put the three-digit alternative first, matching all valid three-digit numbers before trying the next alternative. (For a DFA or POSIX NFA, reordering is unnecessary and pointless: they already choose the longest match.)
Reordering does not fix the first false match. Word boundaries may seem promising, but still match text such as 1.2.3.4.5.6. To prevent such embedded matches, exclude alphanumeric characters and periods on either side. With lookaround, enclose the regex in ˹(?<![\w.])...(?![\w.])˼, requiring that adjacent characters do not match ˹[\w.]˼. Without lookaround, depending on the situation, ˹(^|●)...(●|$)˼ may suffice.
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