473,837 Members | 1,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Multiple regex match idiom

I often have the need to match multiple regexes against a single
string, typically a line of input, like this:

if (matchobj = re1.match(line) ):
... re1 matched; do something with matchobj ...
elif (matchobj = re2.match(line) ):
... re2 matched; do something with matchobj ...
elif (matchobj = re3.match(line) ):
.....

Of course, that doesn't work as written because Python's assignments
are statements rather than expressions. The obvious rewrite results
in deeply nested if's:

matchobj = re1.match(line)
if matchobj:
... re1 matched; do something with matchobj ...
else:
matchobj = re2.match(line)
if matchobj:
... re2 matched; do something with matchobj ...
else:
matchobj = re3.match(line)
if matchobj:
...

Normally I have nothing against nested ifs, but in this case the deep
nesting unnecessarily complicates the code without providing
additional value -- the logic is still exactly equivalent to the
if/elif/elif/... shown above.

There are ways to work around the problem, for example by writing a
utility predicate that passes the match object as a side effect, but
that feels somewhat non-standard. I'd like to know if there is a
Python idiom that I'm missing. What would be the Pythonic way to
write the above code?
May 9 '07 #1
3 2626
Hrvoje Niksic wrote:
I often have the need to match multiple regexes against a single
string, typically a line of input, like this:

if (matchobj = re1.match(line) ):
... re1 matched; do something with matchobj ...
elif (matchobj = re2.match(line) ):
... re2 matched; do something with matchobj ...
elif (matchobj = re3.match(line) ):
....
[snip]
>
There are ways to work around the problem, for example by writing a
utility predicate that passes the match object as a side effect, but
that feels somewhat non-standard. I'd like to know if there is a
Python idiom that I'm missing. What would be the Pythonic way to
write the above code?
Only just learning Python, but to me this seems better.
Completely untested.

re_list = [ re1, re2, re3, ... ]
for re in re_list:
matchob = re.match(line)
if matchob:
....
break

Of course this only works it the "do something" is the same
for all matches. If not, maybe a function for each case,
something like

re1 = re.compile(.... )
def fn1( s, m ):
....
re2 = ....
def fn2( s, m ):
....

re_list = [ (re1, fn1), (re2, fn2), ... ]

for (r,f) in re_list:
matchob = r.match(line)
if matchob:
f( line, matchob )
break
f(line,m)

Probably better ways than this exist.
Charles
May 9 '07 #2
On May 9, 5:00 am, Hrvoje Niksic <hnik...@xemacs .orgwrote:
I often have the need to match multiple regexes against a single
string, typically a line of input, like this:

if (matchobj = re1.match(line) ):
... re1 matched; do something with matchobj ...
elif (matchobj = re2.match(line) ):
... re2 matched; do something with matchobj ...
elif (matchobj = re3.match(line) ):
....

Of course, that doesn't work as written because Python's assignments
are statements rather than expressions. The obvious rewrite results
in deeply nested if's:

matchobj = re1.match(line)
if matchobj:
... re1 matched; do something with matchobj ...
else:
matchobj = re2.match(line)
if matchobj:
... re2 matched; do something with matchobj ...
else:
matchobj = re3.match(line)
if matchobj:
...

Normally I have nothing against nested ifs, but in this case the deep
nesting unnecessarily complicates the code without providing
additional value -- the logic is still exactly equivalent to the
if/elif/elif/... shown above.

There are ways to work around the problem, for example by writing a
utility predicate that passes the match object as a side effect, but
that feels somewhat non-standard. I'd like to know if there is a
Python idiom that I'm missing. What would be the Pythonic way to
write the above code?
Hrvoje,

To make it more elegant I would do this:

1. Put all the ...do somethings... in functions like
re1_do_somethin g(), re2_do_somethin g(),...

2. Create a list of pairs of (re,func) in other words:
dispatch=[ (re1, re1_do_somethin g), (re2, re2_do_somethin g), ... ]

3. Then do:
for regex,func in dispatch:
if regex.match(lin e):
func(...)
Hope this helps,
-Nick Vatamaniuc

May 9 '07 #3
On 9 Mai, 11:00, Hrvoje Niksic <hnik...@xemacs .orgwrote:
I often have the need to match multiple regexes against a single
string, typically a line of input, like this:

if (matchobj = re1.match(line) ):
... re1 matched; do something with matchobj ...
elif (matchobj = re2.match(line) ):
... re2 matched; do something with matchobj ...
elif (matchobj = re3.match(line) ):
....

Of course, that doesn't work as written because Python's assignments
are statements rather than expressions. The obvious rewrite results
in deeply nested if's:

matchobj = re1.match(line)
if matchobj:
... re1 matched; do something with matchobj ...
else:
matchobj = re2.match(line)
if matchobj:
... re2 matched; do something with matchobj ...
else:
matchobj = re3.match(line)
if matchobj:
...

Normally I have nothing against nested ifs, but in this case the deep
nesting unnecessarily complicates the code without providing
additional value -- the logic is still exactly equivalent to the
if/elif/elif/... shown above.

There are ways to work around the problem, for example by writing a
utility predicate that passes the match object as a side effect, but
that feels somewhat non-standard. I'd like to know if there is a
Python idiom that I'm missing. What would be the Pythonic way to
write the above code?
Instead of scanning the same input over and over again with different,
maybe complex, regexes and ugly looking, nested ifs, i would suggest
defining a grammar and do parsing the input once with registered hooks
for your matching expressions.

SimpleParse (http://simpleparse.sourceforge.net) with a
DispatchProcess or or pyparsing (http://pyparsing.wikispaces.com/) in
combination with setParseAction or something similar are your friends
for such a task.

Steffen

May 10 '07 #4

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

Similar topics

1
5157
by: DKode | last post by:
I have the following regex that I am using: Match match = Regex.Match(global, "%(?<column>.+?)%"); my input string (global) is this: "something\%username%\somethingelse\%match2%\some\%match3% I want it to match "username","match2" and "match3" but it only matches %username%, it doesnt continue on and get the other
10
3095
by: Chance Hopkins | last post by:
I'm trying to match a set of matches after some initial text: mytext: "something" "somethingelse" "another thing" "maybe another" (?:mytext: )(?<mymatch>{1,1}+{1,1}+)+ I only get the last one "maybe another". I want to get all the values with quotes as a group, hence the + after the ()'s. Is this possible?
32
14933
by: tshad | last post by:
Can you do a search for more that one string in another string? Something like: someString.IndexOf("something1","something2","something3",0) or would you have to do something like: if ((someString.IndexOf("something1",0) >= 0) || ((someString.IndexOf("something2",0) >= 0) ||
3
8263
by: Craig Buchanan | last post by:
Is there a way to combine these two Replace into a single line? Regex.Replace(Subject, "\&", "&amp;") Regex.Replace(Subject, "\'", "&apos;") Perhaps Regex.Replace(Subject, "{\&|\'}", "{&amp;|&apos;}") Thanks, Craig
2
6015
by: Ed Brown | last post by:
I'm working on a VB.Net application that needs to do quite a bit of string pattern matching, and am having problems using the "LIKE" operator to match the same string twice in the pattern. For example, in the following code: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim theString As String theString = "1234 TEST 5432 TEST ABCD" If theString Like "*TEST*TEST*" Then...
1
1123
by: Aragorn_USA | last post by:
Hi everyone, What I'm trying to do is, to match all the countries in a list, except US and CANADA which is (CA). I tried a lot, but none of mine worked at all. I'm new to regular expressins and I looks completely none sense for me. I need this for work ASAP. Thanks everyone.
10
1890
by: bullockbefriending bard | last post by:
first, regex part: I am new to regexes and have come up with the following expression: ((1|),(1|)/){5}(1|),(1|) to exactly match strings which look like this: 1,2/3,4/5,6/7,8/9,10/11,12 i.e. 6 comma-delimited pairs of integer numbers separated by the
0
2696
by: wbosw | last post by:
I'm trying to create a regex to find more than one capital letter position within a word. The below regex, finds the first capital letter in the word and returns the index for that character. I would like to find both capital letter positions in the word heLLo and return both positions. Does anyone have any suggestions. Thanks in advance, Wbos Public Function FindPosition(ByVal word As String) ' Create a new Regex object....
5
8791
by: mikko.n | last post by:
I have recently been experimenting with GNU C library regular expression functions and noticed a problem with pattern matching. It seems to recognize only the first match but ignoring the rest of them. An example: mikko.c: ----- #include <stdio.h> #include <regex.h>
0
9843
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...
0
10882
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
10275
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
9407
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
7811
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
7005
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
5851
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4045
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3126
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.