1. Computing

Python Regular Expressions (regex): Forming a Regular Expression in Python

From , former About.com Guide

8 of 10

Tightening Python's Grip: Ranges in Python Pattern Matching

Two numbers within curly braces denotes a range in the number of time to repeat the regular expression. Instead of writing "{3}", we could write "{0,3}" and have the same effect. So a single digit within the curly braces like "{3}" effectively begins with an implicit zero.

This is important when you want minimum and maximum thresholds on the number of matches returned. By "the number of matches" is not meant the number of times the regex will match a string (for this you must use iteration). Rather, it is the number of times the regex should be repeated when Python builds the regex for comparison.

For example, say you give re.compile the following regular expression formula:

 "^\S" 

It will match any string that does not begin with whitespace. However, say you give it this regular expression formula:

 "^\S{2,5}" 

Then, Python will construct a regular expression that will match any and all of the following regular expression formulae:

 "^\S\S" 
 "^\S\S\S" 
 "^\S\S\S\S" 
 "^\S\S\S\S\S" 

Note that matches beginning with a single character are not included, and anything with six non-whitespace characters or above are omitted as well.

  1. About.com
  2. Computing
  3. Python
  4. Regular Expressions
  5. Python Regular Expressions - Python Regex - Ranges in Python Pattern Matching

©2013 About.com. All rights reserved.