APEXA, LLC
Blog Gallery Contact

Regular Expression Tutorial, Cheat Sheet, Samples

Blog Date: 12/4/2008

 Recent Blogs << Back

ProJobbers launches job postings 10/28/2008

Microsoft Excel alternating color rows / color ban 11/5/2008

Getting SQL Server table sizes 11/27/2008

 More...
 

IT Jobs Hiring


Cisco Voice Operations Engineer New York, NY

Sr. Software Engineer -- DSP Algorithms, Security Encryption, C/C++ (San Diego, CA ) Los Angeles Area, CA

.NET Developer (Encino) Los Angeles Area, CA

More jobs...
 

Sample usage in C# .NET, which can also be ported to VB .NET:

  // RegEx - strip out area
  rex = new Regex(@"[from]((.|\s)*?\[to])", RegexOptions.IgnoreCase);
  string text = rex.Replace(myString, string.Empty);

Regular Expressions are a powerful pattern matching language that is part of many modern programming languages. Regular Expressions allow you to apply a pattern to an input string and return a list of the matches within the text. Regular expressions also allow text to be replaced using replacement patterns. It is a very powerful version of find and replace.

There are two parts to learning Regular Expressions;

  • learning the Regex syntax
  • learning how to work with Regex in your programming language

This article introduces you to the Regular Expression syntax. After learning the syntax for Regular Expressions you can use it many different languages as the syntax is fairly similar between languages.

Microsoft's .NET Framework contains a set of classes for working with Regular Expressions in the System.Text.RegularExpressions namespace.

The basics - Finding text

Regular Expressions are similar to find and replace in that ordinary characters match themselves. If I want to match the word "went" the Regular Expression pattern would be "went".

Text:    Anna Jones and a friend went to lunch
Regex:   went
Matches: Anna Jones and a friend went to lunch
went

The following are special characters when working with Regular Expressions. They will be discussed throughout the article.

. $ ^ { [ ( | ) * + ? \

Matching any character with dot

The full stop or period character (.) is known as dot. It is a wildcard that will match any character except a new line (\n). For example if I wanted to match the 'a' character followed by any two characters.

Text:    abc def ant cow
Regex:   a..
Matches: abc def ant cow
abc
ant

If the Singleline option is enabled, a dot matches any character including the new line character.

Matching word characters

Backslash and a lowercase 'w' (\w) is a character class that will match any word character. The following Regular Expression matches 'a' followed by two word characters.

Text:    abc anaconda ant cow apple
Regex:   a\w\w
Matches: abc anaconda ant cow apple
abc
ana
ant
app

Backslash and an uppercase 'W' (\W) will match any non-word character.

Matching white-space

White-space can be matched using \s (backslash and 's'). The following Regular Expression matches the letter 'a' followed by two word characters then a white space character.

Text:    "abc anaconda ant"
Regex:   a\w\w\s
Matches: 
"abc "

Note that ant was not matched as it is not followed by a white space character.

White-space is defined as the space character, new line (\n), form feed (\f), carriage return (\r), tab (\t) and vertical tab (\v). Be careful using \s as it can lead to unexpected behaviour by matching line breaks (\n and \r). Sometimes it is better to explicitly specify the characters to match instead of using \s. e.g. to match Tab and Space use [\t\0x0020]

Matching digits

The digits zero to nine can be matched using \d (backslash and lowercase 'd'). For example, the following Regular Expression matches any three digits in a row.

Text:    123 12 843 8472
Regex:   \d\d\d
Matches: 123 12 843 8472
123
843
847

Matching sets of single characters

The square brackets are used to specify a set of single characters to match. Any single character within the set will match. For example, the following Regular Expression matches any three characters where the first character is either 'd' or 'a'.

Text:    abc def ant cow
Regex:   [da]..
Matches: abc def ant cow
abc
def
ant

The caret (^) can be added to the start of the set of characters to specify that none of the characters in the character set should be matched. The following Regular Expression matches any three character where the first character is not 'd' and not 'a'.

Text:    abc def ant cow
Regex:   [^da]..
Matches: 
"bc "
"ef "
"nt "
"cow"

Matching ranges of characters

Ranges of characters can be matched using the hyphen (-). the following Regular Expression matches any three characters where the second character is either 'a', 'b', 'c' or 'd'.

Text:    abc pen nda uml
Regex:   .[a-d].
Matches: abc pen nda uml
abc
nda

Ranges of characters can also be combined together. the following Regular Expression matches any of the characters from 'a' to 'z' or any digit from '0' to '9' followed by two word characters.

Text:    abc no 0aa i8i
Regex:   [a-z0-9]\w\w
Matches: abc no 0aa i8i
abc
0aa
i8i

The pattern could be written more simply as [a-z\d]

Specifying the number of times to match with Quantifiers

Quantifiers let you specify the number of times that an expression must match. The most frequently used quantifiers are the asterisk character (*) and the plus sign (+). Note that the asterisk (*) is usually called the star when talking about Regular Expressions.

Matching zero or more times with star (*)

The star tells the Regular Expression to match the character, group, or character class that immediately precedes it zero or more times. This means that the character, group, or character class is optional, it can be matched but it does not have to match. The following Regular Expression matches the character 'a' followed by zero or more word characters.

Text:    Anna Jones and a friend owned an anaconda
Regex:   a\w*
Options: IgnoreCase
Matches: Anna Jones and a friend owned an anaconda
Anna
and
a
an
anaconda

Matching one or more times with plus (+)

The plus sign tells the Regular Expression to match the character, group, or character class that immediately precedes it one or more times. This means that the character, group, or character class must be found at least once. After it is found once it will be matched again if it follows the first match. The following Regular Expression matches the character 'a' followed by at least one word character.

Text:    Anna Jones and a friend owned an anaconda
Regex:   a\w+
Options: IgnoreCase
Matches: Anna Jones and a friend owned an anaconda
Anna
and
an
anaconda

Note that "a" was not matched as it is not followed by any word characters.

Matching zero or one times with question mark (?)

To specify an optional match use the question mark (?). The question mark matches zero or one times. The following Regular Expression matches the character 'a' followed by 'n' then optionally followed by another 'n'.

Text:    Anna Jones and a friend owned an anaconda
Regex:   an?
Options: IgnoreCase
Matches: Anna Jones and a friend owned an anaconda
An
a
an
a
an
an
a
a

Specifying the number of matches

The minimum number of matches required for a character, group, or character class can be specified with the curly brackets ({n}). The following Regular Expression matches the character 'a' followed by a minimum of two 'n' characters. There must be two 'n' characters for a match to occur.

Text:    Anna Jones and Anne owned an anaconda
Regex:   an{2}
Options: IgnoreCase
Matches: Anna Jones and Anne owned an anaconda
Ann
Ann

A range of matches can be specified by curly brackets with two numbers inside ({n,m}). The first number (n) is the minimum number of matches required, the second (m) is the maximum number of matches permitted. This Regular Expression matches the character 'a' followed by a minimum of two 'n' characters and a maximum of three 'n' characters.

Text:    Anna and Anne lunched with an anaconda annnnnex
Regex:   an{2,3}
Options: IgnoreCase
Matches: Anna and Anne lunched with an anaconda annnnnex
Ann
Ann
annn

The Regex stops matching after the maximum number of matches has been found.

Matching the start and end of a string

To specify that a match must occur at the beginning of a string use the caret character (^). For example, I want a Regular Expression pattern to match the beginning of the string followed by the character 'a'.

Text:    an anaconda ate Anna Jones
Regex:   ^a
Matches: an anaconda ate Anna Jones
"a" at position 1

The pattern above only matches the a in "an".

Note that the caret (^) has different behaviour when used inside the square brackets.

If the Multiline option is on, the caret (^) will match the beginning of each line in a multiline string rather than only the start of the string.

To specify that a match must occur at the end of a string use the dollar character ($). If the Multiline option is on then the pattern will match at the end of each line in a multiline string. This Regular Expression pattern matches the word at the end of the line in a multiline string.

Text:    "an anaconda
ate Anna
Jones"
Regex:   \w+$
Options: Multiline, IgnoreCase
Matches: 
Jones

Microsoft have an online reference for Regex in .NET: Regular Expression Syntax on MSDN


A Great Regular Expression reference for RegEx patterns

Regular expressions can be concatenated to form new regular expressions; if A and B are both regular expressions, then AB is also a regular expression. In general, if a string p matches A and another string q matches B, the string pq will match AB. This holds unless A or B contain low precedence operations; boundary conditions between A and B; or have numbered group references. Thus, complex expressions can easily be constructed from simpler primitive expressions like the ones described here. For details of the theory and implementation of regular expressions, consult the Friedl book referenced above, or almost any textbook about compiler construction.

Regular expressions can contain both special and ordinary characters. Most ordinary characters, like "A", "a", or "0", are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so last matches the string 'last'. (In the rest of this section, we'll write RE's in this special style, usually without quotes, and strings to be matched 'in single quotes'.)

Some characters, like "|" or "(", are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted.

The special characters are:

"."
(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.

 

"^"
(Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.

 

"$"
Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both 'foo' and 'foobar', while the regular expression foo$ matches only 'foo'. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches 'foo2' normally, but 'foo1' in MULTILINE mode.

 

"*"
Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match 'a', 'ab', or 'a' followed by any number of 'b's.

 

"+"
Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match 'a' followed by any non-zero number of 'b's; it will not match just 'a'.

 

"?"
Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either 'a' or 'ab'.

 

*?, +?, ??
The "*", "+", and "?" qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.

 

{m}
Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six "a" characters, but not five.

 

{m,n}
Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 "a" characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match aaaab or a thousand "a" characters followed by a b, but not aaab. The comma may not be omitted or the modifier would be confused with the previously described form.

 

{m,n}?
Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 "a" characters, while a{3,5}? will only match 3 characters.

 

"\"
Either escapes special characters (permitting you to match characters like "*", "?", and so forth), or signals a special sequence; special sequences are discussed below.

If you're not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals; if the escape sequence isn't recognized by Python's parser, the backslash and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it's highly recommended that you use raw strings for all but the simplest expressions.

 

[]
Used to indicate a set of characters. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a "-". Special characters are not active inside sets. For example, [akm$] will match any of the characters "a", "k", "m", or "$"; [a-z] will match any lowercase letter, and [a-zA-Z0-9] matches any letter or digit. Character classes such as \w or \S (defined below) are also acceptable inside a range. If you want to include a "]" or a "-" inside a set, precede it with a backslash, or place it as the first character. The pattern []] will match ']', for example.

You can match the characters not within a range by complementing the set. This is indicated by including a "^" as the first character of the set; "^" elsewhere will simply match the "^" character. For example, [^5] will match any character except "5", and [^^] will match any character except "^".

 

"|"
A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the "|" in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by "|" are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the "|" operator is never greedy. To match a literal "|", use \|, or enclose it inside a character class, as in [|].

 

(...)
Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals "(" or ")", use \( or \), or enclose them inside a character class: [(] [)].

 

(?...)
This is an extension notation (a "?" following a "(" is not meaningful otherwise). The first character after the "?" determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group; (?P<name>...) is the only exception to this rule. Following are the currently supported extensions.

 

(?iLmsux)
(One or more letters from the set "i", "L", "m", "s", "u", "x".) The group matches the empty string; the letters set the corresponding flags (re.I, re.L, re.M, re.S, re.U, re.X) for the entire regular expression. This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the compile() function.

Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined.

 

(?:...)
A non-grouping version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.

 

(?P<name>...)
Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. So the group named 'id' in the example above can also be referenced as the numbered group 1.

For example, if the pattern is (?P<id>[a-zA-Z_]\w*), the group can be referenced by its name in arguments to methods of match objects, such as m.group('id') or m.end('id'), and also by name in pattern text (for example, (?P=id)) and replacement text (such as \g<id>).

 

(?P=name)
Matches whatever text was matched by the earlier group named name.

 

(?#...)
A comment; the contents of the parentheses are simply ignored.

 

(?=...)
Matches if ... matches next, but doesn't consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it's followed by 'Asimov'.

 

(?!...)
Matches if ... doesn't match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it's not followed by 'Asimov'.

 

(?<=...)
Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in "abcdef", since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that abc or a|b are allowed, but a* and a{3,4} are not. Note that patterns which start with positive lookbehind assertions will never match at the beginning of the string being searched; you will most likely want to use the search() function rather than the match() function:

 

>>> import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'

This example looks for a word following a hyphen:

 

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'

 

(?<!...)
Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.

 

(?(id/name)yes-pattern|no-pattern)
Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn't. |no-pattern is optional and can be omitted. For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>) is a poor email matching pattern, which will match with '<user@host.com>' as well as 'user@host.com', but not with '<user@host.com'. New in version 2.4.

 

The special sequences consist of "\" and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. For example, \$ matches the character "$".

\number
Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, (.+) \1 matches 'the the' or '55 55', but not 'the end' (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number. Inside the "[" and "]" of a character class, all numeric escapes are treated as characters.

 

\A
Matches only at the start of the string.

 

\b
Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that \b is defined as the boundary between \w and \ W, so the precise set of characters deemed to be alphanumeric depends on the values of the UNICODE and LOCALE flags. Inside a character range, \b represents the backspace character, for compatibility with Python's string literals.

 

\B
Matches the empty string, but only when it is not at the beginning or end of a word. This is just the opposite of \ b, so is also subject to the settings of LOCALE and UNICODE.

 

\d
When the UNICODE flag is not specified, matches any decimal digit; this is equivalent to the set [0-9]. With UNICODE, it will match whatever is classified as a digit in the Unicode character properties database.

 

\D
When the UNICODE flag is not specified, matches any non-digit character; this is equivalent to the set [^0-9]. With UNICODE, it will match anything other than character marked as digits in the Unicode character properties database.

 

\s
When the LOCALE and UNICODE flags are not specified, matches any whitespace character; this is equivalent to the set [ \t\n\r\f\v]. With LOCALE, it will match this set plus whatever characters are defined as space for the current locale. If UNICODE is set, this will match the characters [ \t\n\r\f\v] plus whatever is classified as space in the Unicode character properties database.

 

\S
When the LOCALE and UNICODE flags are not specified, matches any non-whitespace character; this is equivalent to the set [^ \t\n\r\f\v] With LOCALE, it will match any character not in this set, and not defined as space in the current locale. If UNICODE is set, this will match anything other than [ \t\n\r\f\v] and characters marked as space in the Unicode character properties database.

 

\w
When the LOCALE and UNICODE flags are not specified, matches any alphanumeric character and the underscore; this is equivalent to the set [a-zA-Z0-9_]. With LOCALE, it will match the set [0-9_] plus whatever characters are defined as alphanumeric for the current locale. If UNICODE is set, this will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database.

 

\W
When the LOCALE and UNICODE flags are not specified, matches any non-alphanumeric character; this is equivalent to the set [^a-zA-Z0-9_]. With LOCALE, it will match any character not in the set [0-9_], and not defined as alphanumeric for the current locale. If UNICODE is set, this will match anything other than [0-9_] and characters marked as alphanumeric in the Unicode character properties database.

 

\Z
Matches only at the end of the string.

sources: http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx and www.python.org



12/4/2008 12:20:02 PM

Home | Gallery | Contact | IT Consulting | Web Marketing | Search Engine Optimization | Web Design & CMS | My Blog on C# .NET

Site Map | Copyright 2007 Web Design web design | Developed by APEXA, LLC

APEXA, LLC