473,898 Members | 4,678 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Efficiently test for positive re.match then use the result?

Hello all,

I'm currently befuddled as to how to efficiently test for a positive re.
match then use the results of that match in a function.

Mostly what I've seen people do is to first test for the match, and then
try matching again to get the results. This would seem to be pretty
inefficient to me.

I've tried making the match, then sending it to a variable, then testing
if the variable is good and then finally using it, but this still seems
overkill.

I'm also trying to use this in list comprehensions, mostly because they
are kind of fun. What I've got right now looks something like this.

alist = ['boo','hoo','ch oo']
[re.match('choo' ,line) for line in calist if re.match('choo' ,line)]

[<_sre.SRE_Mat ch object at 0x11e218>]

This is a small test, but what I will be looking for various matches in
is a large special purpose text file.

Does anyone have input on how something like this _should_ be done?
thanks,
--

~elmlish~
Jul 18 '05 #1
1 1492
On 3 Mar 2004, elmlish <- el*****@netscap e.net wrote:
Mostly what I've seen people do is to first test for the match, and then
try matching again to get the results. This would seem to be pretty
inefficient to me.
Where did you see that? Often you see code like:

m = re.match('foo', 'foobar')
if m: do_something with m
I've tried making the match, then sending it to a variable, then testing
if the variable is good and then finally using it, but this still seems
overkill.
It isn't; you can't have directly an return value from assignment in
Python like e.g in C, so you can't write code like:

if m = re.match('foo', 'foobar'): do_somethiing_w ith_m

Global vars are also normally not set from re-matching (you could write
your own matching function which sets a global var; but that's seldom a
good idea ).
I'm also trying to use this in list comprehensions, mostly because they
are kind of fun. What I've got right now looks something like this.
alist = ['boo','hoo','ch oo']
[re.match('choo' ,line) for line in calist if re.match('choo' ,line)] [<_sre.SRE_Mat ch object at 0x11e218>]

This is a small test, but what I will be looking for various matches in
is a large special purpose text file. Does anyone have input on how something like this _should_ be done?
thanks,


I don't know how it _should_ be done but I can tell you how it _could_ be
done.

Use a class like the following:

class Matcher (object):
__slots__ = ('reg', 'match')

def __init__ (self, reg):
self.reg = reg
self.match = None

def __call__ (self, val):
self.match = self.reg(val)
if self.match:
return True

Now you could use it like:
alist = ['boo','hoo','ch oo']
reg = Matcher(re.comp ile('choo').mat ch)
[reg.match for c in alist if reg(c)] [<_sre.SRE_Mat ch object at 0xb3de58>]
That's no overkill.

But if you wanted it even lighter you could use a closure (but don't
tell anyone :-) )

def matcher (reg):
res = [None]
def fun (s):
m = reg(s)
if m: res[0] = m
return m
return res, fun

You use it like that:
res, reg = matcher(re.comp ile('choo').mat ch)
[res[0] for c in alist if reg(c)] [<_sre.SRE_Mat ch object at 0xa14e90>]

Or you simply write:
reg = re.compile('cho o').match
filter(None, [reg(line) for line in alist])

[<_sre.SRE_Mat ch object at 0xb3df38>]
Even for a big list filter(None, ...) is fast.


KP

--
You know you've been sitting in front of your Lisp machine too long
when you go out to the junk food machine and start wondering how to
make it give you the CADR of Item H so you can get that yummie
chocolate cupcake that's stuck behind the disgusting vanilla one.
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6478
by: honda | last post by:
My main table has the following structure: t1 (id_primary, id_secundary, name) i.e. I want to join this table with the following second table: t2 (id_primary, id_secundary, value) i.e. The join should first try to find a match on id_primary and only if that fails it should find a match on id_secundary. Every row in t1 is matched
6
23697
by: WindAndWaves | last post by:
Hi Folks I have inhereted a script that I understand reasonably well, I just do not understand !/^\d+$/.test(el.value) what the hell does that mean? Below is the script (there are really three and they validate a four items
6
1591
by: Karel Miklav | last post by:
If I test() string two times in a row like: var re = new RegExp(expression, "gi"); re.test(s1); re.test(s1); only the first test passes. Is this normal? --
7
5391
by: hasanainf | last post by:
Hi all, I have two querys QueryPurchased ProductID Location TotPcs Prod1 Loc1 100 Prod2 Loc1 50 Prod3 Loc1 150 Prod3 Loc3 150
6
2653
by: Nate Bargmann | last post by:
I am working on a function that takes degrees, minutes, seconds coordinates and converts them to decimal representation. Traditionally, in DMS notation the '-' sign, to indicate west longitude or north latitude, precedes the degree value, e.i. -96° 59' 59". The float type is capable of carrying a signed ZERO for the purpose of representing between 0 and 1 degree west or south. My problem comes from trying to select the correct...
8
10679
by: starffly | last post by:
In my program, the caculated value is supposed to be no more than the constant named MAXINT,otherwise, overflow error will be informed.however, I cannot test if the value exceeds MAXINT within the integer scope smaller than MAXINT,so I want to seek a measure to test the excess without the value's comparing to MAXINT. Please let me know if you have a good idea. THX.
11
2946
by: HopfZ | last post by:
I coudn't understand some behavior of RegExp.test function. Example html code: ---------------- <html><head></head><body><script type="text/javascript"> var r = /^https?:\/\//g; document.write( ); </script></body></html> ---------------------
176
8549
by: nw | last post by:
Hi, I previously asked for suggestions on teaching testing in C++. Based on some of the replies I received I decided that best way to proceed would be to teach the students how they might write their own unit test framework, and then in a lab session see if I can get them to write their own. To give them an example I've created the following UTF class (with a simple test program following). I would welcome and suggestions on how anybody...
5
2324
by: vbgunz | last post by:
/* * BEGIN EXAMPLES */ var text = 'A Cats Catalog of Cat Catastrophes and Calamities'; /*** * EXAMPLE 1: negative lookahead assertion logic ***/
0
9842
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11265
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10859
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10954
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
10487
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
9662
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
8036
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
7191
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();...
1
4708
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.