Advertisement
codemonkey

regex_tester.py

Oct 12th, 2012
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.09 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # Encoding: UTF-8
  3. """This script launches a GUI for testing regular expressions."""
  4.  
  5. import sys
  6. import os
  7. import re
  8. import sre_constants
  9. from textwrap import dedent
  10.  
  11. try:
  12.     import wx
  13.     import wx.aui
  14.     import wx.lib.anchors as anchors
  15. except ImportError:
  16.     print "This script requires wxPython."
  17.     sys.exit(1)
  18.  
  19. class RegexTesterFrame(wx.Frame):
  20.     def __init__(self):
  21.         wx.Frame.__init__(
  22.             self, None, -1, 'Regex tester', (100, 100),
  23.             (1024, 768), wx.DEFAULT_FRAME_STYLE
  24.         )
  25.         # wx.Frame.__init__(
  26.         #     self, None, -1, 'Regex tester', wx.DefaultPosition,
  27.         #     wx.DefaultSize, wx.DEFAULT_FRAME_STYLE
  28.         # )
  29.  
  30.         self.initialize_components()
  31.  
  32.         self.statusbar = self.CreateStatusBar(1, wx.ST_SIZEGRIP)
  33.         self.statusbar.SetFieldsCount(2)
  34.         self.statusbar.SetStatusWidths([-1, -3])
  35.         self.statusbar.SetStatusText('Welcome to the RegEx tester!', 0)
  36.  
  37.     def initialize_components(self):
  38.         self._mgr = wx.aui.AuiManager()
  39.         self._mgr.SetManagedWindow(self)
  40.  
  41.         self.SetMinSize(wx.Size(800, 400))
  42.  
  43.         # Create a toolbar for the regex modifiers (flags).
  44.         self._mgr.AddPane(
  45.             self.create_flags_panel(),
  46.             wx.aui.AuiPaneInfo().Name('modifiers').ToolbarPane().Top()
  47.         )
  48.  
  49.         # Create a toolbar for the regex modifiers (flags).
  50.         self._mgr.AddPane(
  51.             self.create_functions_panel(),
  52.             wx.aui.AuiPaneInfo().Name('functions').ToolbarPane().Top()
  53.         )
  54.  
  55.         # Create the text input pane.
  56.         self._mgr.AddPane(
  57.             self.create_text_input_panel(),
  58.             wx.aui.AuiPaneInfo().Name('text_input').Caption('Text input').
  59.                 CloseButton(False).Left().Layer(1).BestSize((600, 100))
  60.         )
  61.  
  62.         # Create the regex pane.
  63.         self._mgr.AddPane(
  64.             self.create_regex_panel(),
  65.             wx.aui.AuiPaneInfo().Name('regex').Caption('Regex').
  66.                 CloseButton(False).Top().BestSize((200, 100))
  67.         )
  68.  
  69.         # Create the output pane.
  70.         self._mgr.AddPane(
  71.             self.create_output_panel(),
  72.             wx.aui.AuiPaneInfo().Name('output').CloseButton(False).CenterPane().
  73.                 BestSize((200, 300))
  74.         )
  75.  
  76.         self._mgr.Update()
  77.  
  78.         self.Bind(wx.EVT_CLOSE, self.on_close)
  79.  
  80.     def create_flags_panel(self):
  81.         panel = wx.Panel(self, -1)
  82.  
  83.         # Create the check boxes.
  84.         self.flag_dotall_checkbox = wx.CheckBox(panel, -1, 'DOTALL')
  85.         self.flag_ic_checkbox = wx.CheckBox(panel, -1, 'IGNORECASE')
  86.         self.flag_ext_checkbox = wx.CheckBox(panel, -1, 'VERBOSE')
  87.         self.flag_multiline_checkbox = wx.CheckBox(panel, -1, 'MULTILINE')
  88.  
  89.         # Check ignore case by default.
  90.         self.flag_ic_checkbox.SetValue(True)
  91.  
  92.         # Bind the change event to run the update function.
  93.         for checkbox in [self.flag_dotall_checkbox, self.flag_ic_checkbox,
  94.                          self.flag_ext_checkbox, self.flag_multiline_checkbox]:
  95.             self.Bind(
  96.                 wx.EVT_CHECKBOX,
  97.                 self.update_output_event,
  98.                 checkbox
  99.             )
  100.  
  101.         # Create the layout sizer.
  102.         sizer = wx.BoxSizer()
  103.         sizer.Add(wx.StaticText(panel, -1, 'Flags: '))
  104.         sizer.Add(self.flag_dotall_checkbox)
  105.         sizer.Add(self.flag_ic_checkbox)
  106.         sizer.Add(self.flag_ext_checkbox)
  107.         sizer.Add(self.flag_multiline_checkbox)
  108.  
  109.         # Create the outer sizer and add the inner sizer to it.
  110.         outer_sizer = wx.BoxSizer()
  111.         outer_sizer.Add(sizer, border=5, flag=wx.ALL)
  112.  
  113.         # Apply the outer sizer to the panel and return it.
  114.         panel.SetSizerAndFit(outer_sizer)
  115.  
  116.         return panel
  117.  
  118.     def create_functions_panel(self):
  119.         panel = wx.Panel(self, -1)
  120.  
  121.         # Create the radio buttons.
  122.         self.func_search_radio = wx.RadioButton(panel, -1, 'Search')
  123.         self.func_match_radio = wx.RadioButton(panel, -1, 'Match')
  124.         self.func_findall_radio = wx.RadioButton(panel, -1, 'Find all')
  125.  
  126.         # Check the search function radio button by default.
  127.         self.func_search_radio.SetValue(True)
  128.  
  129.         # Bind the radio buttons' change events to update the output.
  130.         for radio in [self.func_search_radio, self.func_match_radio,
  131.                       self.func_findall_radio]:
  132.             self.Bind(wx.EVT_RADIOBUTTON, self.update_output_event, radio)
  133.  
  134.         # Add the radio buttons to the sizer.
  135.         sizer = wx.BoxSizer(wx.HORIZONTAL)
  136.         sizer.Add(wx.StaticText(panel, -1, 'Function: '))
  137.         sizer.AddMany([
  138.             self.func_search_radio,
  139.             self.func_match_radio,
  140.             self.func_findall_radio
  141.         ])
  142.  
  143.         # Create the outer sizer and add the inner sizer to it.
  144.         outer_sizer = wx.BoxSizer()
  145.         outer_sizer.Add(sizer, border=5, flag=wx.ALL)
  146.  
  147.         panel.SetSizerAndFit(outer_sizer)
  148.  
  149.         return panel
  150.  
  151.     def create_regex_panel(self):
  152.         panel = wx.Panel(self)
  153.         self.regex_textbox = wx.TextCtrl(
  154.             panel, style=wx.NO_BORDER | wx.TE_MULTILINE
  155.         )
  156.  
  157.         sizer = wx.BoxSizer()
  158.         sizer.Add(self.regex_textbox, proportion=1, flag=wx.EXPAND)
  159.  
  160.         panel.SetSizerAndFit(sizer)
  161.  
  162.         # Bind the text change event.
  163.         self.Bind(
  164.             wx.EVT_TEXT,
  165.             self.update_output_event,
  166.             self.regex_textbox
  167.         )
  168.  
  169.         return panel
  170.  
  171.     def create_text_input_panel(self):
  172.         panel = wx.Panel(self)
  173.         self.input_textbox = wx.TextCtrl(
  174.             panel, style=wx.NO_BORDER | wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.HSCROLL
  175.         )
  176.  
  177.         sizer = wx.BoxSizer()
  178.         sizer.Add(self.input_textbox, proportion=1, flag=wx.EXPAND)
  179.  
  180.         panel.SetSizerAndFit(sizer)
  181.  
  182.         # Bind the text change event.
  183.         self.Bind(
  184.             wx.EVT_TEXT,
  185.             self.update_output_event,
  186.             self.input_textbox
  187.         )
  188.  
  189.         return panel
  190.  
  191.     def create_output_panel(self):
  192.         panel = wx.Panel(self)
  193.         sizer = wx.BoxSizer(wx.VERTICAL)
  194.  
  195.         self.output_textbox = wx.TextCtrl(
  196.             panel, -1, style=wx.TE_MULTILINE | wx.TE_READONLY
  197.         )
  198.  
  199.         sizer.Add(wx.StaticText(panel, -1, 'Output:'), border=5,
  200.                   flag=wx.ALL | wx.TOP | wx.LEFT | wx.RIGHT)
  201.         sizer.Add(self.output_textbox, proportion=1, border=10,
  202.                   flag=wx.EXPAND | wx.ALL)
  203.  
  204.         panel.SetSizerAndFit(sizer)
  205.         return panel
  206.  
  207.     def update_output_event(self, event):
  208.         self.update_output()
  209.  
  210.     def update_output(self):
  211.         """Function that checks the values in all controls and updates the
  212.        output."""
  213.         r = self.regex_textbox.GetValue()
  214.         text = self.input_textbox.GetValue()
  215.  
  216.         # Fetch the regex flags.
  217.         flags = 0
  218.  
  219.         if self.flag_dotall_checkbox.GetValue():
  220.             flags |= re.DOTALL
  221.         if self.flag_ic_checkbox.GetValue():
  222.             flags |= re.IGNORECASE
  223.         if self.flag_ext_checkbox.GetValue():
  224.             flags |= re.VERBOSE
  225.         if self.flag_multiline_checkbox.GetValue():
  226.             flags |= re.MULTILINE
  227.  
  228.         # Fetch the function choice.
  229.         if self.func_search_radio.GetValue():
  230.             fn = re.search
  231.         elif self.func_match_radio.GetValue():
  232.             fn = re.match
  233.         elif self.func_findall_radio.GetValue():
  234.             fn = re.findall
  235.         else:
  236.             wx.MessageBox('None of the functions are chosen... Somehow.')
  237.             return
  238.  
  239.         # Try to perform the regex match. On error, display the error in the
  240.         # status bar.
  241.         try:
  242.             result = fn(r, text, flags)
  243.         except sre_constants.error as e:
  244.             msg = 'Regex compilation error: ' + e.message
  245.             self.SetStatusText(msg, 1)
  246.             return
  247.  
  248.         # Empty the error part of the status bar just in case.
  249.         self.SetStatusText('', 1)
  250.  
  251.         # If there is a result to the match or search function.
  252.         if result and fn is not re.findall:
  253.             output = dedent(u"""
  254.                Match: {}
  255.  
  256.                Groups: {}
  257.  
  258.                Group dict: {}
  259.            """)
  260.  
  261.             output = output.format(
  262.                 repr(result.group()),
  263.                 repr(result.groups()),
  264.                 repr(result.groupdict())
  265.             )
  266.  
  267.         # If there is a findall result.
  268.         elif result and fn is re.findall:
  269.             output = u"Matches: " + repr(result)
  270.  
  271.         # No result.
  272.         else:
  273.             output = u"No matches."
  274.  
  275.         # Set the result text.
  276.         self.output_textbox.SetValue(output)
  277.  
  278.     def on_close(self, event):
  279.         self._mgr.UnInit()
  280.         del self._mgr
  281.         self.Destroy()
  282.  
  283. class RegexTesterApp(wx.App):
  284.     def OnInit(self):
  285.         mainframe = RegexTesterFrame()
  286.         mainframe.Show()
  287.  
  288.         self.SetTopWindow(mainframe)
  289.         return True
  290.  
  291. def main():
  292.     app = RegexTesterApp(True)
  293.     app.MainLoop()
  294.  
  295. if __name__ == '__main__':
  296.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement