• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2
3"""Basic regular expression demonstration facility (Perl style syntax)."""
4
5from tkinter import *
6import re
7
8class ReDemo:
9
10    def __init__(self, master):
11        self.master = master
12
13        self.promptdisplay = Label(self.master, anchor=W,
14                text="Enter a Perl-style regular expression:")
15        self.promptdisplay.pack(side=TOP, fill=X)
16
17        self.regexdisplay = Entry(self.master)
18        self.regexdisplay.pack(fill=X)
19        self.regexdisplay.focus_set()
20
21        self.addoptions()
22
23        self.statusdisplay = Label(self.master, text="", anchor=W)
24        self.statusdisplay.pack(side=TOP, fill=X)
25
26        self.labeldisplay = Label(self.master, anchor=W,
27                text="Enter a string to search:")
28        self.labeldisplay.pack(fill=X)
29        self.labeldisplay.pack(fill=X)
30
31        self.showframe = Frame(master)
32        self.showframe.pack(fill=X, anchor=W)
33
34        self.showvar = StringVar(master)
35        self.showvar.set("first")
36
37        self.showfirstradio = Radiobutton(self.showframe,
38                                         text="Highlight first match",
39                                          variable=self.showvar,
40                                          value="first",
41                                          command=self.recompile)
42        self.showfirstradio.pack(side=LEFT)
43
44        self.showallradio = Radiobutton(self.showframe,
45                                        text="Highlight all matches",
46                                        variable=self.showvar,
47                                        value="all",
48                                        command=self.recompile)
49        self.showallradio.pack(side=LEFT)
50
51        self.stringdisplay = Text(self.master, width=60, height=4)
52        self.stringdisplay.pack(fill=BOTH, expand=1)
53        self.stringdisplay.tag_configure("hit", background="yellow")
54
55        self.grouplabel = Label(self.master, text="Groups:", anchor=W)
56        self.grouplabel.pack(fill=X)
57
58        self.grouplist = Listbox(self.master)
59        self.grouplist.pack(expand=1, fill=BOTH)
60
61        self.regexdisplay.bind('<Key>', self.recompile)
62        self.stringdisplay.bind('<Key>', self.reevaluate)
63
64        self.compiled = None
65        self.recompile()
66
67        btags = self.regexdisplay.bindtags()
68        self.regexdisplay.bindtags(btags[1:] + btags[:1])
69
70        btags = self.stringdisplay.bindtags()
71        self.stringdisplay.bindtags(btags[1:] + btags[:1])
72
73    def addoptions(self):
74        self.frames = []
75        self.boxes = []
76        self.vars = []
77        for name in ('IGNORECASE',
78                     'MULTILINE',
79                     'DOTALL',
80                     'VERBOSE'):
81            if len(self.boxes) % 3 == 0:
82                frame = Frame(self.master)
83                frame.pack(fill=X)
84                self.frames.append(frame)
85            val = getattr(re, name).value
86            var = IntVar()
87            box = Checkbutton(frame,
88                    variable=var, text=name,
89                    offvalue=0, onvalue=val,
90                    command=self.recompile)
91            box.pack(side=LEFT)
92            self.boxes.append(box)
93            self.vars.append(var)
94
95    def getflags(self):
96        flags = 0
97        for var in self.vars:
98            flags = flags | var.get()
99        return flags
100
101    def recompile(self, event=None):
102        try:
103            self.compiled = re.compile(self.regexdisplay.get(),
104                                       self.getflags())
105            bg = self.promptdisplay['background']
106            self.statusdisplay.config(text="", background=bg)
107        except re.error as msg:
108            self.compiled = None
109            self.statusdisplay.config(
110                    text="re.error: %s" % str(msg),
111                    background="red")
112        self.reevaluate()
113
114    def reevaluate(self, event=None):
115        try:
116            self.stringdisplay.tag_remove("hit", "1.0", END)
117        except TclError:
118            pass
119        try:
120            self.stringdisplay.tag_remove("hit0", "1.0", END)
121        except TclError:
122            pass
123        self.grouplist.delete(0, END)
124        if not self.compiled:
125            return
126        self.stringdisplay.tag_configure("hit", background="yellow")
127        self.stringdisplay.tag_configure("hit0", background="orange")
128        text = self.stringdisplay.get("1.0", END)
129        last = 0
130        nmatches = 0
131        while last <= len(text):
132            m = self.compiled.search(text, last)
133            if m is None:
134                break
135            first, last = m.span()
136            if last == first:
137                last = first+1
138                tag = "hit0"
139            else:
140                tag = "hit"
141            pfirst = "1.0 + %d chars" % first
142            plast = "1.0 + %d chars" % last
143            self.stringdisplay.tag_add(tag, pfirst, plast)
144            if nmatches == 0:
145                self.stringdisplay.yview_pickplace(pfirst)
146                groups = list(m.groups())
147                groups.insert(0, m.group())
148                for i in range(len(groups)):
149                    g = "%2d: %r" % (i, groups[i])
150                    self.grouplist.insert(END, g)
151            nmatches = nmatches + 1
152            if self.showvar.get() == "first":
153                break
154
155        if nmatches == 0:
156            self.statusdisplay.config(text="(no match)",
157                                      background="yellow")
158        else:
159            self.statusdisplay.config(text="")
160
161
162# Main function, run when invoked as a stand-alone Python program.
163
164def main():
165    root = Tk()
166    demo = ReDemo(root)
167    root.protocol('WM_DELETE_WINDOW', root.quit)
168    root.mainloop()
169
170if __name__ == '__main__':
171    main()
172