Welcome, guest | Sign In | My Account | Store | Cart

Teaches you regex in python by trying it out.

>>> only one command called compile allows you to compile a certain string
>>> any other input is treated as pattern to match
Python, 41 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/python

#
# tests regex with matches
# handy utility to learn regex in python

#(c)lostp, 2010 December

#version 0.0.1

import re

class AppModel:
  pass

AppModel.regexstr = ''
AppModel.matchstr = ''

def main():
    while(1):
        line = raw_input("REGEX>")
        l = line.split()
        if (line[:7] == 'compile'):
            try:
                AppModel.regexstr = l[1]
                AppModel.compiledobj = re.compile(AppModel.regexstr)
            except:
                print "%s is not a valid regex" % AppModel.regexstr
                continue
        else:
            AppModel.matchstr = line
            matches()

def matches():
    if AppModel.compiledobj.match(AppModel.matchstr):
        print "%s matches the pattern %s" % (AppModel.matchstr,AppModel.regexstr)
    else:
        print "%s does not match the pattern %s" % (AppModel.matchstr,AppModel.regexstr)

if __name__ == '__main__':
    main()
Created by Lost Protocol on Fri, 17 Dec 2010 (MIT)
Python recipes (4591)
Lost Protocol's recipes (2)

Required Modules

Other Information and Tasks