Using Expression Modifiers
With the special symbols above, the following characters are treated as modifiers that can be used to match against a previous sub-pattern zero, one, or more times:
{N}
Match the sub-pattern exactly N times
{N,}
Match the sub-pattern N or more times
{N,M}
Match at least N times and no more than M times
?
Match the sub-pattern 0 or 1 times; same as {0,1}
*
Match the sub-pattern 0 or more times; same as {0,}
+
Match the sub-pattern 1 or more times; same as {1,}
Modifiers can be used to reduce the size of the expression and to specify optional parts of the expression. They are useful when combined with parentheses to designate sub-patterns.
The pattern
/Se(rial)?\d+/\d+/
matches any serial interface designator, either in the short form (Se0/0
) or the long form (Serial12/45
).
Examples:
$Vendor like /Cis(co)?/ $
ifType like /Se(rial)?\d+[/]\d+/
You use regular expressions to match values selected from a larger database of values. For economy of effort, it is sometimes easier to specify “just enough” of a pattern to obtain the match. For example, though a valid IPv4 address is formatted as “A.B.C.D” where A, B, C, and D range from 0 to 255, an expression:
/^(\d{1-3}\.){3}254$/
ensures that the first three octets are in fact defined as numbers with dots in between, but is unnecessary to find all addresses ending with “.254” when a simpler expression
/\.254$/
which checks for the desired suffix will succeed.