Nearing the End

Quick Regular Expression Test

I wrote a regular expression and it didn't work as expected on the first try. So here's a little Python program I used to determine where it broke down.

Source Code

import re

line = '# 1 "SfmexDeclarations.h" 1'                                                                             
pattern = '^\s*# \d{1,6} (?P".+?")( \d){0,1}$'

for i in range(1, len(pattern)+1):
    p = pattern[:i]
    try:         m = re.match(p, line)
        if m:
            print '[%s]\t[%s]' % (p, line[m.start(): m.end()-m.start()])
    except re.error, e:
        print '[%s]\tError: %s' % (p, e)
        pass

Output

pattern = '^\s*# \d{1,6} (?P".+?")( \d){0,1}$'

[^]     []
[^\]    Error: bogus escape (end of line)
[^\s*]  []
[^\s*#] [#]
[^\s*# ]        [# ]
[^\s*# \]       Error: bogus escape (end of line)
[^\s*# \d]      [# 1]
[^\s*# \d{1,6}] [# 1]
[^\s*# \d{1,6} ]        [# 1 ]
[^\s*# \d{1,6} (]       Error: unbalanced parenthesis
[^\s*# \d{1,6} (?]      Error: unexpected end of pattern
[^\s*# \d{1,6} (?P]     Error: unexpected end of pattern
[^\s*# \d{1,6} (?P<] Error: unterminated name
[^\s*# \d{1,6} (?P<p]        Error: unterminated name
[^\s*# \d{1,6} (?P<p1]       Error: unterminated name
[^\s*# \d{1,6} (?P<p1>]   Error: unbalanced parenthesis
[^\s*# \d{1,6} (?P<p1>"]  Error: unbalanced parenthesis
[^\s*# \d{1,6} (?P<p1>".] Error: unbalanced parenthesis
[^\s*# \d{1,6} (?P<p1>".+]        Error: unbalanced parenthesis
[^\s*# \d{1,6} (?P<p1>".+?]       Error: unbalanced parenthesis
[^\s*# \d{1,6} (?P<p1>".+?"]      Error: unbalanced parenthesis
[^\s*# \d{1,6} (?P<p1>".+?")]     [# 1 "SfmexDeclarations.h"]
[^\s*# \d{1,6} (?P<p1>".+?")(]    Error: unbalanced parenthesis
[^\s*# \d{1,6} (?P<p1>".+?")( ]   Error: unbalanced parenthesis
[^\s*# \d{1,6} (?P<p1>".+?")( \]  Error: bogus escape (end of line)
[^\s*# \d{1,6} (?P<p1>".+?")( \d] Error: unbalanced parenthesis
[^\s*# \d{1,6} (?P<p1>".+?")( \d)]        [# 1 "SfmexDeclarations.h" 1]
[^\s*# \d{1,6} (?P<p1>".+?")( \d){0,1}]   [# 1 "SfmexDeclarations.h" 1]
[^\s*# \d{1,6} (?P<p1>".+?")( \d){0,1}$]  [# 1 "SfmexDeclarations.h" 1]