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: -
def OnTextEntered(self, evt):
-
text = self.GetValue()
-
if re.search('\[', text) and not re.search('\]', text):
-
text.replace('[', '\[')
-
if self.DoSearch(text, evt):
-
if text not in self.searches:
-
self.searches.append(text)
-
if len(self.searches) > self.maxSearches:
-
del self.searches[0]
-
self.SetMenu(self.MakeMenu())
-
And the doSearch function... -
def DoSearch(self, text, event=None):
-
if not len(self.data_bak):
-
return False
-
-
# 10014 is the Event type for wx.EVT_MENU
-
# 10164 is the Event type for wx.EVT_TEXT (adaptive search)
-
# 10165 is the Event type for wx.EVT_TEXT_ENTER
-
valid_events = [10014, 10165]
-
-
regex = re.compile(text.upper())
-
tool = self.tb.FindById(Global.OnTB_ActSearch_Id)
-
if tool.IsToggled():
-
self.lc.DeleteAllItems()
-
for entry in range(len(self.data_bak)):
-
if text:
-
if regex.search(self.data_bak[entry][0].upper()):
-
self.lc.Append(self.data_bak[entry])
-
else:
-
self.lc.Append(self.data_bak[entry])
-
return False
-
elif not tool.IsToggled() and event.GetEventType() in valid_events:
-
idx = self.lc.FindItem(self.currentItem + 1, text, True)
-
if idx != -1:
-
self.lc.Focus(idx)
-
self.lc.Select(idx)
-
return True
-
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.
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: - import re
-
>>> s = 'PrmID['
-
>>> re.sub('[[]', '[', s)
-
'PrmID['
-
>>>
So, it seems that you could use: 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: - import re
-
>>> s = 'PrmID['
-
>>> re.sub('[[]', '[', s)
-
'PrmID['
-
>>>
So, it seems that you could use:
Good point Barton. I checked it out also: - >>> s = 'P_SWID_PrmID[0]'
-
>>> searchStr = 'Prmid['
-
>>> import re
-
>>> patt = re.compile(searchStr.replace('[', '[[]'), re.IGNORECASE)
-
>>> m = patt.search(s)
-
>>> m
-
<_sre.SRE_Match object at 0x00D5A9C0>
-
>>> patt = re.compile(searchStr, re.IGNORECASE)
-
Traceback (most recent call last):
-
File "<interactive input>", line 1, in ?
-
File "C:\Python23\lib\sre.py", line 179, in compile
-
return _compile(pattern, flags)
-
File "C:\Python23\lib\sre.py", line 230, in _compile
-
raise error, v # invalid expression
-
error: unexpected end of regular expression
-
>>> patt.findall(s)
-
['PrmID[']
-
>>>
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!
Sign in to post your reply or Sign up for a free account.
Similar topics |
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!
|
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
|
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 =
|
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!!
|
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)" ...
| |
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
|
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.
|
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.
|
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...
|
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...
|
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,...
| |
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...
|
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...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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...
| |