473,495 Members | 2,128 Online
Bytes | Software Development & Data Engineering Community
Create 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','choo']
[re.match('choo',line) for line in calist if re.match('choo',line)]

[<_sre.SRE_Match 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 1469
On 3 Mar 2004, elmlish <- el*****@netscape.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_with_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','choo']
[re.match('choo',line) for line in calist if re.match('choo',line)] [<_sre.SRE_Match 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','choo']
reg = Matcher(re.compile('choo').match)
[reg.match for c in alist if reg(c)] [<_sre.SRE_Match 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.compile('choo').match)
[res[0] for c in alist if reg(c)] [<_sre.SRE_Match object at 0xa14e90>]

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

[<_sre.SRE_Match 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
6462
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. ...
6
23377
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...
6
1569
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
5358
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
2630
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...
8
10646
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...
11
2897
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;...
176
8184
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...
5
2292
by: vbgunz | last post by:
/* * BEGIN EXAMPLES */ var text = 'A Cats Catalog of Cat Catastrophes and Calamities'; /*** * EXAMPLE 1: negative lookahead assertion logic ***/
0
7120
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,...
0
6991
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...
1
6878
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...
0
7373
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...
1
4897
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...
0
3078
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1405
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 ...
1
649
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
286
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...

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.