472,983 Members | 2,653 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,983 software developers and data experts.

Actively searching with Regular Expressions

jlm699
314 100+
I have an application that is build on wxPython and have run into a small but annoying problem. I use a Search Control in my toolbar just as in the ToolBar example. Now when the user enters say PrmID[ ... this gets passed to a regular expression search function, however this obviously raises the exception saying that there is an unexpected end to the regular expression. What I would like to do is replace '[' with '\[', however using the string.replace function yields 'PrmID\\[' (escaping the escape character, but not the character I would like to have escaped). My code of what I've tried is as follows:

Expand|Select|Wrap|Line Numbers
  1.    def OnTextEntered(self, evt):
  2.         text = self.GetValue()
  3.         if re.search('\[', text) and not re.search('\]', text):
  4.             text.replace('[', '\[')
  5.         if self.DoSearch(text, evt):
  6.             if text not in self.searches:
  7.                 self.searches.append(text)
  8.                 if len(self.searches) > self.maxSearches:
  9.                     del self.searches[0]
  10.                 self.SetMenu(self.MakeMenu())
  11.  
And the doSearch function...
Expand|Select|Wrap|Line Numbers
  1.     def DoSearch(self,  text, event=None):
  2.         if not len(self.data_bak):
  3.             return False
  4.  
  5.         # 10014 is the Event type for wx.EVT_MENU
  6.         # 10164 is the Event type for wx.EVT_TEXT (adaptive search)
  7.         # 10165 is the Event type for wx.EVT_TEXT_ENTER
  8.         valid_events = [10014, 10165]
  9.  
  10.         regex = re.compile(text.upper())
  11.         tool = self.tb.FindById(Global.OnTB_ActSearch_Id)
  12.         if tool.IsToggled():
  13.             self.lc.DeleteAllItems()
  14.             for entry in range(len(self.data_bak)):
  15.                 if text:
  16.                     if regex.search(self.data_bak[entry][0].upper()):
  17.                         self.lc.Append(self.data_bak[entry])
  18.                 else:
  19.                     self.lc.Append(self.data_bak[entry])
  20.             return False
  21.         elif not tool.IsToggled() and event.GetEventType() in valid_events:
  22.             idx = self.lc.FindItem(self.currentItem + 1, text, True)
  23.             if idx != -1:
  24.                 self.lc.Focus(idx)
  25.                 self.lc.Select(idx)
  26.             return True
  27.  
BTW, basically this application has a listing of Parameter names and values in a ListControl (self.lc), which when initially opened is backed-up by a two-dimensional array (self.data_bak).
This 'active search' will modify what the user sees in the listctrl (making sure to update the back-up as well), just as they type it (I wanted to reproduce the Search function from the upper right corner of iTunes). The toggle check is there because the user has a toggle button on the toolbar to turn this active search on or off.
So if anybody has any ideas as to how to replace '[' in a string with literally '\[' I would appreciate it. I've played around with raw strings and even tried using a crazy combination of raw strings and the repr function to no avail.

An example of parameter names is P_SWID_PrmID[0].

To reiterate, I simply need to take the user input and escape any bracket characters so that the regex.search function does not mistake it for the start/end of a regular expression character class.
Jul 30 '07 #1
3 2169
bartonc
6,596 Expert 4TB
I'm not too familiar with regular expressions yet, but how 'buot making a character class of one character? re doesn't mind the the syntax of this pattern:
Expand|Select|Wrap|Line Numbers
  1. import re
  2. >>> s = 'PrmID['
  3. >>> re.sub('[[]', '[', s)
  4. 'PrmID['
  5. >>> 
So, it seems that you could use:
Expand|Select|Wrap|Line Numbers
  1. s.replace('[', '[[]')
Jul 30 '07 #2
bvdet
2,851 Expert Mod 2GB
I'm not too familiar with regular expressions yet, but how 'buot making a character class of one character? re doesn't mind the the syntax of this pattern:
Expand|Select|Wrap|Line Numbers
  1. import re
  2. >>> s = 'PrmID['
  3. >>> re.sub('[[]', '[', s)
  4. 'PrmID['
  5. >>> 
So, it seems that you could use:
Expand|Select|Wrap|Line Numbers
  1. s.replace('[', '[[]')
Good point Barton. I checked it out also:
Expand|Select|Wrap|Line Numbers
  1. >>> s = 'P_SWID_PrmID[0]'
  2. >>> searchStr = 'Prmid['
  3. >>> import re
  4. >>> patt = re.compile(searchStr.replace('[', '[[]'), re.IGNORECASE)
  5. >>> m = patt.search(s)
  6. >>> m
  7. <_sre.SRE_Match object at 0x00D5A9C0>
  8. >>> patt = re.compile(searchStr, re.IGNORECASE)
  9. Traceback (most recent call last):
  10.   File "<interactive input>", line 1, in ?
  11.   File "C:\Python23\lib\sre.py", line 179, in compile
  12.     return _compile(pattern, flags)
  13.   File "C:\Python23\lib\sre.py", line 230, in _compile
  14.     raise error, v # invalid expression
  15. error: unexpected end of regular expression
  16. >>> patt.findall(s)
  17. ['PrmID[']
  18. >>> 
Jul 31 '07 #3
jlm699
314 100+
Wow, thanks guys! That's elegant yet so simple! I was lazy and just replaced every occurance of '[' or ']' with '.' (I figured, if the user knows that much of the name they'll know the number contained within the brackets so actually finding a match to the bracket wasn't too terribly important)

But thanks for the great suggestions!
Aug 9 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Richard Berg | last post by:
Hello, I need to search a byte array for a sequence of bytes. The sequence may include wildcards. For example if the array contains 0xAA, 0xBB, 0xAA, OxDD then I want to be able to search for...
2
by: ajitgoel | last post by:
Hi; I need some simple help with my regular expressions. I want to search my input text for all the boolean variables which do not start with bln. i.e I want to match "bool followed by 1 or...
2
by: Sehboo | last post by:
Hi, I have several regular expressions that I need to run against documents. Is it possible to combine several expressions in one expression in Regex object. So that it is faster, or will I...
7
by: Brian Mitchell | last post by:
Is there an easy way to pull a date/time stamp from a string? The DateTime stamp is located in different parts of each string and the DateTime stamp could be in different formats (mm/dd/yy or...
4
by: Egyd Csaba | last post by:
Hi All, I'd like to "compress" the following two filter expressions into one - assuming that it makes sense regarding query execution performance. .... where (adate LIKE "2004.01.10 __:30" or...
7
by: Billa | last post by:
Hi, I am replaceing a big string using different regular expressions (see some example at the end of the message). The problem is whenever I apply a "replace" it makes a new copy of string and I...
10
by: Phil Latio | last post by:
How do I use wildcards when searching in array? At least that's what I think I need !! I have the line: if ($attribute != "id") The above is not 100% correct because it should also be...
4
by: Costa | last post by:
I am looking for a c/c++ text search engine library that supports: - free text searching - not only beginning of words but substrings as well - wildcard searching - I want strings such as...
2
by: Bart Kastermans | last post by:
I have a file in which I am searching for the letter "i" (actually a bit more general than that, arbitrary regular expressions could occur) as long as it does not occur inside an expression that...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.