473,545 Members | 721 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pattern matching with string and list

Hi,

I'd need to perform simple pattern matching within a string using a
list of possible patterns. For example, I want to know if the substring
starting at position n matches any of the string I have a list, as
below:

sentence = "the color is $red"
patterns = ["blue","red","y ellow"]
pos = sentence.find($ )
# here I need to find whether what's after 'pos' matches any of the
strings of my 'patterns' list
bmatch = ismatching( sentence[pos:], patterns)

Is an equivalent of this ismatching() function existing in some Python
lib?

Thanks,

Olivier.

Dec 12 '05 #1
5 5736
ol****@gmail.co m wrote:
Hi,

I'd need to perform simple pattern matching within a string using a
list of possible patterns. For example, I want to know if the substring
starting at position n matches any of the string I have a list, as
below:

sentence = "the color is $red"
patterns = ["blue","red","y ellow"]
pos = sentence.find($ )
# here I need to find whether what's after 'pos' matches any of the
strings of my 'patterns' list
bmatch = ismatching( sentence[pos:], patterns)

Is an equivalent of this ismatching() function existing in some Python
lib?

Thanks,

Olivier.

As I think you define it, ismatching can be written as:
def ismatching(sent ence, patterns): ... re_pattern = re.compile("(%s )\Z" % "|".join(patter ns))
... return bool(re_pattern .match(sentence ))
... ismatching(sent ence[pos+1:], patterns) True ismatching(sent ence[pos+1:], ["green", "blue"]) False (For help with regular expressions, see: http://www.amk.ca/python/howto/regex/)
or, you can ask the regexp engine to starting looking at a point you specify:
def ismatching(sent ence, patterns, startingpos = 0): ... re_pattern = re.compile("(%s )\Z" % "|".join(patter ns))
... return bool(re_pattern .match(sentence , startingpos))
... ismatching(sent ence, patterns, pos+1) True

but, you may be able to save the separate step of determining pos, by including
it in the regexp, e.g.,
def matching(patter ns, sentence): ... re_pattern = re.compile("\$( %s)" % "|".join(patter ns))
... return bool(re_pattern .search(sentenc e))
... matching(patter ns, sentence) True matching(["green", "blue"], sentence) False
then, it might be more general useful to return the match, rather than the
boolean value - you can still use it in truth testing, since a no-match will
evaluate to False
def matching(patter ns, sentence): ... re_pattern = re.compile("\$( %s)" % "|".join(patter ns))
... return re_pattern.sear ch(sentence)
... if matching(patter ns, sentence): print "Match" ...
Match

Finally, if you are going to be doing a lot of these it would be faster to take
the pattern compilation out of the function, and simply use the pre-compiled
regexp, or as below, its bound method: search:
matching = re.compile("\$( %s)\Z" % "|".join(patter ns)).search
matching(senten ce) <_sre.SRE_Mat ch object at 0x01847E60> bool(_) True bool(matching(" the color is $red but there is more")) False bool(matching(" the color is $pink")) False bool(matching(" the $color is $red")) True


HTH

Michael


Dec 13 '05 #2
On Mon, 12 Dec 2005 ol****@gmail.co m wrote:
I'd need to perform simple pattern matching within a string using a list
of possible patterns. For example, I want to know if the substring
starting at position n matches any of the string I have a list, as
below:

sentence = "the color is $red"
patterns = ["blue","red","y ellow"]
pos = sentence.find($ )
I assume that's a typo for "sentence.find( '$')", rather than some new
syntax i've not learned yet!
# here I need to find whether what's after 'pos' matches any of the
strings of my 'patterns' list
bmatch = ismatching( sentence[pos:], patterns)

Is an equivalent of this ismatching() function existing in some Python
lib?


I don't think so, but it's not hard to write:

def ismatching(targ et, patterns):
for pattern in patterns:
if target.startswi th(pattern):
return True
return False

You don't say what bmatch should be at the end of this, so i'm going with
a boolean; it would be straightforward to return the pattern which
matched, or the index of the pattern which matched in the pattern list, if
that's what you want.

The tough guy way to do this would be with regular expressions (in the re
module); you could do the find-the-$ and the match-a-pattern bit in one
go:

import re
patternsRe = re.compile(r"\$ (blue)|(red)|(y ellow)")
bmatch = patternsRe.sear ch(sentence)

At the end, bmatch is None if it didn't match, or an instance of re.Match
(from which you can get details of the match) if it did.

If i was doing this myself, i'd be a bit cleaner and use non-capturing
groups:

patternsRe = re.compile(r"\$ (?:blue)|(?:red )|(?:yellow)")

And if i did want to capture the colour string, i'd do it like this:

patternsRe = re.compile(r"\$ ((?:blue)|(?:re d)|(?:yellow))" )

If this all looks like utter gibberish, DON'T PANIC! Regular expressions
are quite scary to begin with (and certainly not very regular-looking!),
but they're actually quite simple, and often a very powerful tool for text
processing (don't get carried way, though; regular expressions are a bit
like absinthe, in that a little helps your creativity, but overindulgence
makes you use perl).

In fact, we can tame the regular expressions quite neatly by writing a
function which generates them:

def regularly_expre ss_patterns(pat terns):
pattern_regexps = map(
lambda pattern: "(?:%s)" % re.escape(patte rn),
patterns)
regexp = r"\$(" + "|".join(patter n_regexps) + ")"
return re.compile(rege xp)

patternsRe = regularly_expre ss_patterns(pat terns)

tom

--
limited to concepts that are meta, generic, abstract and philosophical --
IEEE SUO WG
Dec 13 '05 #3
Taking you literally, I'm not sure you need regex. If you know or can
find position n, then can't you just:

sentence = "the color is $red"
patterns = ["blue","red","y ellow"]
pos = sentence.find(" $")
for x in patterns:
if x==sentence[pos+1:]:
print x, pos+1

But maybe I'm oversimplifying .

rpd

Dec 13 '05 #4
Even without the marker, can't you do:

sentence = "the fabric is red"
colors = ["red", "white", "blue"]

for color in colors:
if (sentence.find( color) > 0):
print color, sentence.find(c olor)

Dec 13 '05 #5
BartlebyScriven er wrote:
Even without the marker, can't you do:

sentence = "the fabric is red"
colors = ["red", "white", "blue"]

for color in colors:
if (sentence.find( color) > 0):
print color, sentence.find(c olor)

That depends on whether you're only looking for whole words:
colors = ['red', 'green', 'blue']
def findIt(sentence ): .... for color in colors:
.... if sentence.find(c olor) > 0:
.... print color, sentence.find(c olor)
.... findIt("This is red") red 8 findIt("Fredrik Lundh") red 1


It's easy to see all the cases that this approach will fail for...
Dec 13 '05 #6

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

Similar topics

8
6970
by: gsv2com | last post by:
One of my weaknesses has always been pattern matching. Something I definitely need to study up on and maybe you guys can give me a pointer here. I'm looking to remove all of this code and just use pattern matching to determine if the proper amount of numeric characters has been met. Here is the function I've already done. Any help you can...
176
8005
by: Thomas Reichelt | last post by:
Moin, short question: is there any language combining the syntax, flexibility and great programming experience of Python with static typing? Is there a project to add static typing to Python? Thank you, -- greetz tom
3
1744
by: Greg Lindstrom | last post by:
Hello- I'm running Python 2.2.3 on Windows XP "Professional" and am reading a file wit 1 very long line of text (the line consists of multiple records with no cr/lf). What I would like to do is scan for the occurrence of a specific pattern of characters which I expect to repeat many times in the file. Suppose I want to search for "Start:...
9
3189
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # Matching string patterns # # Sometimes you want to know if a string is of # particular pattern. Let's say in your website # you have converted all images files from gif # format to png format. Now you need to change the # html code to use the .png files. So, essentially
1
2721
by: Henry | last post by:
I have a table that stores a list of zip codes using a varchar column type, and I need to perform some string prefix pattern matching search. Let's say that I have the columns: 94000-1235 94001 94100 If I run a pattern matching search for the string "940", then I should get the top two rows of data back. If I run a pattern matching...
2
342
by: Joecx | last post by:
Hi If I want to copy files using a pattern like: I want all files on a directory that start with 20050822 to be copied to a different directory. I can't get file.copy or copyfile to accept *.* pattern matching. Does anyone have the code to make this work? Thanx if you can help!
1
7010
by: Sea Sharper | last post by:
Hi, C#, from a FileSystemWatcher I would like to catch all files with a *.* filter but then inside the event handler compare against a list of wildcards (eg '*.abc;*.def') Is there anywhere inside the Framework where I can do something like Pattern x = new Pattern("*.abc"); if ( x.Matches(strFilename) )
9
5056
by: Jim Lewis | last post by:
Anyone have experience with string pattern matching? I need a fast way to match variables to strings. Example: string - variables ============ abcaaab - xyz abca - xy eeabcac - vxw x matches abc
7
2410
by: Captain Dondo | last post by:
I'm working on a terminal emulator for an embedded system. The key requirements are small size, code clarity, maintainability, and portability. We have machines that regularly see a service life of 30 years so it's not impossible that this code will be around that long. I'm trying to use termcap info to map incoming strings to display...
0
7465
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...
0
7398
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...
0
7656
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. ...
0
7805
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...
1
7416
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...
1
5325
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...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1878
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
1
1013
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.