473,809 Members | 2,625 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Actively searching with Regular Expressions

jlm699
314 Contributor
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 2207
bartonc
6,596 Recognized Expert Expert
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 Recognized Expert Moderator Specialist
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 Contributor
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
4411
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 0xAA, 0x?? and get two matches... I've been all around Google but still can't find any suggestions on how anything like this can be implemented..... Can someone please give me a clue? Some well-known algorithm maybe? Thanks!
2
2038
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 more spaces followed by text other than bln" in my input text. Eg: 1. private bool dispose; should be highlighted 2. private bool blndispose; should be not be highlighted
2
5107
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 have to use all the expressions seperately? Here are my regular expressions that check for valid email address and link Dim Expression As String =
7
2664
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 dd/mm/yyyy, or hh:mm:ss dd/mm...etc.) Any ideas would be appreciated, Thanks!!
4
5187
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 adate LIKE "2004.01.10 __:15") .... into something like this: .... where adate LIKE "2004.01.10 __:(30/15)" ...
7
3834
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 want to avoid that. My question here is if there is a way to pass either a memory stream or array of "find", "replace" expressions or any other way to avoid multiple copies of a string. Any help will be highly appreciated
10
2331
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 looking for anything ending with id. eg. bookid or authorid aswell as just id.
4
3013
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 *test* to be supported - regular expressions I know about clucene, but, unless I am mistaken, lucene doesn't support, for instance, having the * at the beginning of the searched text, and it doesn't seem to support searching substrings.
2
1518
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 matches \\.+?\b (something started by a backslash and including the word that follows). More concrete example, I have the string "\sin(i)" and I want to match the argument, but not the i in \sin. Can this be achieved by combining the regular...
0
9722
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10391
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10121
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.