473,386 Members | 1,773 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 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 2191
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: Együd 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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.