473,671 Members | 2,580 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

checking a string against multiple patterns

Hi,

here is a piece of pseudo-code (taken from Ruby) that illustrates the
problem I'd like to solve in Python:

str = 'abc'
if str =~ /(b)/ # Check if str matches a pattern
str = $` + $1 # Perform some action
elsif str =~ /(a)/ # Check another pattern
str = $1 + $' # Perform some other action
elsif str =~ /(c)/
str = $1
end

The task is to check a string against a number of different patterns
(containing groupings).
For each pattern, different actions need to be taken.

In Python, a single match of this kind can be done as follows:

str = 'abc'
match = re.search( '(b)' , str )
if match: str = str[0:m.start()] + m.group(1) # I'm not sure if
this way of accessing 'pre-match'
# is
optimal, but let's ignore it now

The problem is that you you can't extend this example to multiple
matches with 'elif'
because the match must be performed separately from the conditional.

This obviously won't work in Python:

if match=re.search ( pattern1 , str ):
...
elif match=re.search ( pattern2 , str ):
...

So the only way seems to be:

match = re.search( pattern1 , str ):
if match:
....
else:
match = re.search( pattern2 , str ):
if match:
....
else:
match = re.search( pattern3 , str ):
if match:
....

and we end up having a very nasty, multiply-nested code.

Is there an alternative to it? Am I missing something? Python doesn't
have special variables $1, $2 (right?) so you must assign the result
of a match to a variable, to be able to access the groups.

I'd appreciate any hints.

Tomasz



Dec 18 '07 #1
5 22042
kib
tomasz a écrit :
Is there an alternative to it? Am I missing something? Python doesn't
have special variables $1, $2 (right?) so you must assign the result
of a match to a variable, to be able to access the groups.
Hi Thomasz,

See ie :

http://www.regular-expressions.info/python.html [Search and Replace section]

And you'll see that Python supports numbered groups and even named
groups in regular expressions.

Christophe K.
Dec 18 '07 #2
On 18 dic, 09:41, tomasz <tmkm...@google mail.comwrote:
Hi,

here is a piece of pseudo-code (taken from Ruby) that illustrates the
problem I'd like to solve in Python:

str = 'abc'
if str =~ /(b)/ # Check if str matches a pattern
str = $` + $1 # Perform some action
elsif str =~ /(a)/ # Check another pattern
str = $1 + $' # Perform some other action
elsif str =~ /(c)/
str = $1
end

The task is to check a string against a number of different patterns
(containing groupings).
For each pattern, different actions need to be taken.

In Python, a single match of this kind can be done as follows:

str = 'abc'
match = re.search( '(b)' , str )
if match: str = str[0:m.start()] + m.group(1) # I'm not sure if
this way of accessing 'pre-match'
# is
optimal, but let's ignore it now

The problem is that you you can't extend this example to multiple
matches with 'elif'
because the match must be performed separately from the conditional.

This obviously won't work in Python:

if match=re.search ( pattern1 , str ):
...
elif match=re.search ( pattern2 , str ):
...

So the only way seems to be:

match = re.search( pattern1 , str ):
if match:
....
else:
match = re.search( pattern2 , str ):
if match:
....
else:
match = re.search( pattern3 , str ):
if match:
....

and we end up having a very nasty, multiply-nested code.
Define a small function with each test+action, and iterate over them
until a match is found:

def check1(input):
match = re.search(patte rn1, input)
if match:
return input[:match.end(1)]

def check2(input):
match = re.search(patte rn2, input)
if match:
return ...

def check3(input):
match = ...
if match:
return ...

for check in check1, check2, check3:
result = check(input)
if result is not None:
break
else:
# no match found

--
Gabriel Genellina
Dec 18 '07 #3
On Dec 18, 1:41 pm, tomasz <tmkm...@google mail.comwrote:
Hi,

here is a piece of pseudo-code (taken from Ruby) that illustrates the
problem I'd like to solve in Python:

str = 'abc'
if str =~ /(b)/ # Check if str matches a pattern
str = $` + $1 # Perform some action
elsif str =~ /(a)/ # Check another pattern
str = $1 + $' # Perform some other action
elsif str =~ /(c)/
str = $1
end

The task is to check a string against a number of different patterns
(containing groupings).
For each pattern, different actions need to be taken.
In the `re.sub` function (and `sub` method of regex object), the
`repl` parameter can be a callback function as well as a string:

http://docs.python.org/lib/node46.html

Does that help?

Eg.

def multireplace(te xt, mapping):
rx = re.compile('|'. join(re.escape( key) for key in mapping))
def callback(match) :
key = match.group(0)
repl = mapping[key]
log.info("Repla cing '%s' with '%s'", key, repl)
return repl
return rx.subn(callbac k, text)

(I'm not sure, but I think I adapted this from: http://effbot.org/zone/python-replace.htm)

Gerard
Dec 18 '07 #4
tomasz <tm*****@google mail.comwrites:
here is a piece of pseudo-code (taken from Ruby) that illustrates the
problem I'd like to solve in Python:
[...]

I asked the very same question in
http://groups.google.com/group/comp....eb5631ade8b393
It seems that people either write more elaborate constructs or learn
to tolerate the nesting.
Is there an alternative to it?
A simple workaround is to write a trivial function that returns a
boolean, and also stores the match object in either a global storage
or an object. It's not really elegant, especially in smaller scripts,
but it works:

def search(pattern, s, store):
match = re.search(patte rn, s)
store.match = match
return match is not None

class MatchStore(obje ct):
pass # irrelevant, any object with a 'match' attr would do

where = MatchStore()
if search(pattern1 , s, where):
pattern1 matched, matchobj in where.match
elif search(pattern2 , s, where):
pattern2 matched, matchobj in where.match
....
Dec 18 '07 #5
On Dec 18, 4:41 am, tomasz <tmkm...@google mail.comwrote:
Is there an alternative to it? Am I missing something? Python doesn't
have special variables $1, $2 (right?) so you must assign the result
of a match to a variable, to be able to access the groups.

I'd appreciate any hints.
Don't use regexes for something as simple as this. Try find().

Most of the time I use regexes in perl (90%+) I am doing something
that can be done much better using the string methods and some simple
operations. Plus, it turns out to be faster than perl usually.
Dec 18 '07 #6

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

Similar topics

0
1159
by: RJN | last post by:
Hi My web service receives an object of type say MyObject. I want to serialize this object,and then validate the xml against the main xsd. When validation happens, it should also validate against the included schema. The main schema includes one more schema and the actual types are described in the included schema.
4
23311
by: DraguVaso | last post by:
Hi, For my VB.NET application I have the following situation: 2 tables on my SQL Server: tblAccounts and tblRules. For each Account there are many Rules (so tblRules is linked to my tblAccounts by the Account). In the tblAccounts thee is a field Company which occurs many times (there is more than one Account for each Company:). Whet I want to do on my Fom is this: I have a combobox with all my company's in it. When I choce a Company...
5
37810
by: Jason | last post by:
Is there a mechanism in VB.NET that allows something like: If myVar In ("A","B","C") Then... The way I'm doing it now is: Select Case myVar Case "A","B","C" Or like this:
0
1121
by: RJN | last post by:
hi My web service receives an object of type say MyObject. I want to serialize this object,and then validate the xml against the main xsd. When validation happens, it should also validate against the included schema. The main schema includes one more schema and the actual types are described in the included schema.
5
4946
by: paul_zaoldyeck | last post by:
does anyone know how to validate an xml file against multiple defined schema? can you show me some examples? i'm making here an xml reader.. thank you
4
18764
by: abcd | last post by:
I am using fnmatch.fnmatch to find some files. The only problem I have is that it only takes one pattern...so if I want to search using multiple patterns I have to do something like.... patterns = for p in patterns: if fnmatch.fnmatch(some_file_name, p): return True
1
4224
by: vang | last post by:
How do I find out which delimiter if found/used when splitting a string with multiple delimiters are defined in a char array? Example: dim i as integer dim returnText as string dim InputText as string = "apples/orange\banana" dim delim as char = {"\", "/", "$")
4
3024
by: ziycon | last post by:
I have a string passed in and I want to check validate it to make sure that multiple values don't exist at the start, the below would only check the entire string for the value?? if(strstr($string,array("value1","value2","value3")) { ... }
1
11817
by: Anil Verma | last post by:
How to compare a SQL variable against multiple values: Here is the scenario; Declare @JobTitle varchar(10) Select @JobTitle = JobTitle from tableName where xxx=xxx Now I want to compare @JobTitle value against multiple strings without using OR in the IF statement?
0
8485
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
8403
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
8930
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
8677
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
7446
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
6238
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
5704
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
2819
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
2
2062
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.