Regular Expressions

Introduction

Regular Expressions are a widely-used method of specifying patterns of text to search for. Special metacharacters allow you to specify, for instance, that a particular string you are looking for, occurs at the beginning, or end of a line, or contains n recurrences of a certain character.

Simple matches

Any single character matches itself, unless it is a metacharacter with a special meaning described below. A series of characters matches that series of characters in the target string, so the pattern "short" would match "short" in the target string. You can cause characters that normally function as metacharacters or escape sequences to be interpreted by preceding them with a backslash "\".
For instance, metacharacter "^" matches beginning of string, but "\^" matches character "^", and "\\" matches "\", etc.

Examples :

    unsigned matches string 'unsigned'
    \^unsigned matches string '^unsigned'

Escape sequences

Characters may be specified using a escape sequences: "\n" matches a newline, "\t" a tab, etc. More generally, \xnn, where nn is a string of hexadecimal digits, matches the character whose ASCII value is nn.
If you need wide (Unicode) character code, you can use '\x{nnnn}', where 'nnnn' - one or more hexadecimal digits.

    \xnn - char with hex code nn
    \x{nnnn)- char with hex code nnnn (one byte for plain text and two bytes for Unicode)
    \t - tab (HT/TAB), same as \x09
    \n - newline (NL), same as \x0a
    \r - car.return (CR), same as \x0d
    \f - form feed (FF), same as \x0c
    \a - alarm (bell) (BEL), same as \x07
    \e - escape (ESC) , same as \x1b

Examples:

    unsigned\x20int matches 'unsigned int' (note space in the middle)
    \tunsigned matches 'unsigned' (predecessed by tab)

Character classes

You can specify a character class, by enclosing a list of characters in [], which will match any of the characters from the list. If the first character after the "[" is "^", the class matches any character not in the list.

Examples:

    count[aeiou]r finds strings 'countar', 'counter', etc. but not 'countbr', 'countcr', etc.
    count[^aeiou]r finds strings 'countbr', 'countcr', etc. but not 'countar', 'counter', etc.
Within a list, the "-" character is used to specify a range, so that a-z represents all characters between "a" and "z", inclusive.

If you want "-" itself to be a member of a class, put it at the start or end of the list, or precede it with a backslash.
If you want ']', you may place it at the start of list or precede it with a backslash.

Examples:

    [-az] matches 'a', 'z' and '-'
    [az-] matches 'a', 'z' and '-'
    [a\-z] matches 'a', 'z' and '-'
    [a-z] matches all twenty six small characters from 'a' to 'z'
    [\n-\x0D] matches any of #10,#11,#12,#13.
    [\d-t] matches any digit, '-' or 't'.
    []-a] matches any char from ']'..'a'.

Metacharacters

Metacharacters are special characters which are the essence of regular expressions. There are different types of metacharacters, described below.

Metacharacters - Line separators

    ^ - start of line
    $ - end of line
    \A - start of text
    \Z - end of text
    . - any character in line

Examples:

    ^GPIO_PORTA - matches string ' GPIO_PORTA ' only if it's at the beginning of line
    GPIO_PORTA$ - matches string ' GPIO_PORTA ' only if it's at the end of line
    ^GPIO_PORTA$ - matches string ' GPIO_PORTA ' only if it's the only string in line
    PORT.r - matches strings like 'GPIO_PORTA', 'GPIO_PORTB', 'PORT1' and so on

The "^" metacharacter by default is only guaranteed to match beginning of the input string/text, and the "$" metacharacter only at the end. Embedded line separators will not be matched by ^" or "$".
You may, however, wish to treat a string as a multi-line buffer, such that the "^" will match after any line separator within the string, and "$" will match before any line separator.
Regular expressions works with line separators as recommended at http://www.unicode.org/unicode/reports/tr18/

Metacharacters - Predefined classes

    \w - an alphanumeric character (including "_")
    \W - a nonalphanumeric character
    \d - a numeric character
    \D - a non-numeric character
    \s - any space (same as [\t\n\r\f])
    \S - a non space

You may use \w, \d and \s within custom character classes.

Example:
    routi\de - matches strings like 'routi1e', 'routi6e' and so on, but not 'routine', 'routime' and so on.

Metacharacters - Word boundaries

A word boundary ("\b") is a spot between two characters that has an alphanumeric character ("\w") on one side, and a nonalphanumeric character ("\W") on the other side (in either order), counting the imaginary characters off the beginning and end of the string as matching a "\W".

    \b - match a word boundary)
    \B - match a non-(word boundary)

Metacharacters - Iterators

Any item of a regular expression may be followed by another type of metacharacters - iterators. Using this metacharacters,you can specify number of occurences of previous character, metacharacter or subexpression.

    * - zero or more ("greedy"), similar to {0,}
    + - one or more ("greedy"), similar to {1,}
    ? - zero or one ("greedy"), similar to {0,1}
    {n} - exactly n times ("greedy")
    {n,} - at least n times ("greedy")
    {n,m} - at least n but not more than m times ("greedy")
    *? - zero or more ("non-greedy"), similar to {0,}?
    +? - one or more ("non-greedy"), similar to {1,}?
    ?? - zero or one ("non-greedy"), similar to {0,1}?
    {n}? - exactly n times ("non-greedy")
    {n,}? - at least n times ("non-greedy")
    {n,m}? - at least n but not more than m times ("non-greedy")

So, digits in curly brackets of the form, {n,m}, specify the minimum number of times to match the item n and the maximum m. The form {n} is equivalent to {n,n} and matches exactly n times. The form {n,} matches n or more times. There is no limit to the size of n or m, but large numbers will chew up more memory and slow down execution.

If a curly bracket occurs in any other context, it is treated as a regular character.

Examples:
    count.*r ß- matches strings like 'counter', 'countelkjdflkj9r' and 'countr'
    count.+r - matches strings like 'counter', 'countelkjdflkj9r' but not 'countr'
    count.?r - matches strings like 'counter', 'countar' and 'countr' but not 'countelkj9r'
    counte{2}r - matches string 'counteer'
    counte{2,}r - matches strings like 'counteer', 'counteeer', 'counteeer' etc.
    counte{2,3}r - matches strings like 'counteer', or 'counteeer' but not 'counteeeer'

A little explanation about "greediness". "Greedy" takes as many as possible, "non-greedy" takes as few as possible.
For example, 'b+' and 'b*' applied to string 'abbbbc' return 'bbbb', 'b+?' returns 'b', 'b*?' returns empty string, 'b{2,3}?' returns 'bb', 'b{2,3}' returns 'bbb'.

Metacharacters - Alternatives

You can specify a series of alternatives for a pattern using "|" to separate them, so that bit|bat|bot will match any of "bit", "bat", or "bot" in the target string as would "b(i|a|o)t)". The first alternative includes everything from the last pattern delimiter ("(", "[", or the beginning of the pattern) up to the first "|", and the last alternative contains everything from the last "|" to the next pattern delimiter. For this reason, it's common practice to include alternatives in parentheses, to minimize confusion about where they start and end.

Alternatives are tried from left to right, so the first alternative found for which the entire expression matches, is the one that is chosen. This means that alternatives are not necessarily greedy. For example: when matching rou|rout against "routine", only the "rou" part will match, as that is the first alternative tried, and it successfully matches the target string (this might not seem important, but it is important when you are capturing matched text using parentheses.) Also remember that "|" is interpreted as a literal within square brackets, so if you write [bit|bat|bot], you're really only matching [biao|].

Examples:
    rou(tine|te) - matches strings 'routine' or 'route'.

Metacharacters - Subexpressions

The bracketing construct ( ... ) may also be used for define regular subexpressions. Subexpressions are numbered based on the left to right order of their opening parenthesis. First subexpression has number '1'

Examples:
    (int){8,10} matches strings which contain 8, 9 or 10 instances of the 'int'
    routi([0-9]|a+)e matches 'routi0e', 'routi1e' , 'routine', 'routinne', 'routinnne' etc.

Metacharacters - Backreferences

Metacharacters \1 through \9 are interpreted as backreferences. \ matches previously matched subexpression #.

Examples:
    (.)\1+ matches 'aaaa' and 'cc'.
    (.+)\1+ matches 'abab' and '123123'
    (['"]?)(\d+)\1 matches "13" (in double quotes), or '4' (in single quotes) or 77 (without quotes) etc
Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code