473,785 Members | 2,283 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

creating an (inefficent) alternating regular expression from a listof options

Pyparsing has a really nice feature that I want in PLY. I want to
specify a list of strings and have them converted to a regular
expression.

A Perl module which does an aggressively optimizing job of this is
Regexp::List -
http://search.cpan.org/~dankogai/Reg...Regexp/List.pm

I really dont care if the expression is optimal. So the goal is
something like:

vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu|
u|ii|i)'

Is there a public module available for this purpose?
Sep 9 '08 #1
8 1337
metaperl.com wrote:
Pyparsing has a really nice feature that I want in PLY. I want to
specify a list of strings and have them converted to a regular
expression.

A Perl module which does an aggressively optimizing job of this is
Regexp::List -
http://search.cpan.org/~dankogai/Reg...Regexp/List.pm

I really dont care if the expression is optimal. So the goal is
something like:

vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu|
u|ii|i)'

Is there a public module available for this purpose?

Perhaps I'm missing something but your function call oneOf(...) is longer than
than actually specifying the result.

You can certainly write quite easily:

def oneOf(s):
return "|".join(s.spli t())

-Larry
Sep 9 '08 #2
>I really dont care if the expression is optimal. So the goal is
something like:
>vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu|
u|ii|i)'
>Is there a public module available for this purpose?
Check Ka-Ping Yee's rxb module:

http://lfw.org/python/

Needs translating from the old regex module to the current re module, but it
shouldn't take a lot of effort. You can find regex docs in old
distributions (probably through 2.1 or 2.2?). Also, check PyPI to see if
someone has already updated rxb for use with re.

Skip

Sep 9 '08 #3
On Tue, 09 Sep 2008 08:19:04 -0500, Larry Bates wrote:
>I really dont care if the expression is optimal. So the goal is
something like:

vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu|
u|ii|i)'

Is there a public module available for this purpose?
Perhaps I'm missing something but your function call oneOf(...) is
longer than than actually specifying the result.

You can certainly write quite easily:

def oneOf(s):
return "|".join(s.spli t())
I'd throw `re.escape()` into that function just in case `s` contains
something with special meaning in regular expressions.

Ciao,
Marc 'BlackJack' Rintsch
Sep 9 '08 #4
metaperl.com <me******@gmail .comwrote:
Pyparsing has a really nice feature that I want in PLY. I want to
specify a list of strings and have them converted to a regular
expression.

A Perl module which does an aggressively optimizing job of this is
Regexp::List -
http://search.cpan.org/~dankogai/Reg...Regexp/List.pm

I really dont care if the expression is optimal. So the goal is
something like:

vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu|
u|ii|i)'

Is there a public module available for this purpose?
I wrote one of these in perl a while ago

http://www.craig-wood.com/nick/pub/words-to-regexp.pl

It transforms the regular expression recursively into more efficient
ones. It uses regular expressions to do that. I considered porting
it to python but looking at the regular expressions made me feel weak
at the knees ;-)

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Sep 9 '08 #5
On Sep 9, 9:12 am, "metaperl.c om" <metap...@gmail .comwrote:
Pyparsing has a really nice feature that I want in PLY. I want to
specify a list of strings and have them converted to a regular
expression.

A Perl module which does an aggressively optimizing job of this is
Regexp::List -http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/Lis...

I really dont care if the expression is optimal. So the goal is
something like:

vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu|
u|ii|i)'

Is there a public module available for this purpose?
I was about to start a thread about a very similar problem; hope I'm
not hijacking this thread. However I am interested in a solution that
(1) scales to a potentially large number of alternate strings
(hundreds or thousands), which will hit, sooner or later, some max
limit in the builtin regexps and (2) is not limited to strings but can
be used for arbitrary objects. Therefore I am looking for a different
approach, perhaps a specialization of the general regexp search
algorithm.

More formally, given (a) an input sequence I and (b) a set of
'censored' sequences S, find and remove all the sequences in S that
appear in I. For instance, if
S = set([(a,), (a,b), (a,c), (c,), (d,a)])
and
I = (x, a, b, c, y, d, a, b), the filtered sequence would be:
O = (x, y, b)
i.e. the censored subsequences are (a,b), (c,), and (d,a).

As with regexps, if sequence `x` is a prefix of `y`, the longer
sequence `y` wins when both match (e.g. if (a,b) matches, it
supersedes (a,)).

For extra bonus, the algorithm should remove overlapping subsequences
too, i.e. for the input I above, the output would be (x, y) since both
(d,a) and (a,b) would match for (d,a,b).

With respect to complexity, I am mainly interested in len(S); len(I)
is small for my application, typically no more than 10. Of course, an
algorithm that scales decently in both len(S) and len(I) would be even
better. Any ideas or relevant links ?

George

PS: This is not a homework ;)
Sep 9 '08 #6
Larry Bates wrote:
>vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu|
u|ii|i)'

Is there a public module available for this purpose?

Perhaps I'm missing something but your function call oneOf(...) is
longer than than actually specifying the result.

You can certainly write quite easily:

def oneOf(s):
return "|".join(s.spli t())
"|" works strictly from left to right, so that doesn't quite work since
it doesn't place "aa" before "a". a simple reverse sort will take care
of that:

return "|".join(sorted (s.split(), reverse=True))

you may also want to do re.escape on all the words, to avoid surprises
when the choices contain special characters.

</F>

Sep 9 '08 #7
On Sep 9, 9:23*am, s...@pobox.com wrote:
* * >I really dont care if theexpressionis optimal. So the goal is
* * >something like:

* * >vowel_regexp = oneOf("a aa i ii u uu".split()) *# yieldingr'(aa|a |uu|
* * >u|ii|i)'

* * >Is there a public module available for this purpose?

Check Ka-Ping Yee's rxb module:

* *http://lfw.org/python/
Ok <http://lfw.org/python/rxb.py>
suffers from the possibility of putting shorter match before longer
one:

def either(*alterna tives):
options = []
for option in alternatives:
options.append( makepat(option) .regex)
return Pattern('\(' + string.join(opt ions, '|') + '\)')

>*Also, check PyPI to see if
someone has already updated rxb for use with re.
No one has - http://pypi.python.org/pypi?%3Aactio...&submit=search

no results returned

Sep 18 '08 #8
On Sep 9, 12:42*pm, Fredrik Lundh <fred...@python ware.comwrote:
>
you may also want to do re.escape on all the words, to avoid surprises
when the choices contain special characters.
yes, thank you very much:

import re

def oneOf(s):
alts = sorted(s.split( ), reverse=True)
alts = [re.escape(s) for s in alts]
return "|".join(al ts)

Sep 18 '08 #9

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

Similar topics

4
3231
by: Neri | last post by:
Some document processing program I write has to deal with documents that have headers and footers that are unnecessary for the main processing part. Therefore, I'm using a regular expression to go over each document, find out if it contains a header and/or a footer and extract only the main content part. The headers and the footers have no specific format and I have to detect and remove them using a list of strings that may appear as...
1
4239
by: | last post by:
Hi, I have a Regular Expression that will match the format a user provides in a textbox. Ex. Brown,Joe in the textbox I would like the expression to have both whitespace and non-whitespace options after the comma.
14
11485
by: olekristianvillabo | last post by:
I have a regular expression that is approximately 100k bytes. (It is basically a list of all known norwegian postal numbers and the corresponding place with | in between. I know this is not the intended use for regular expressions, but it should nonetheless work. the pattern is ur'(N-|NO-)?(5259 HJELLESTAD|4026 STAVANGER|4027 STAVANGER........|8305 SVOLVÆR)' The error message I get is:
9
3359
by: Pete Davis | last post by:
I'm using regular expressions to extract some data and some links from some web pages. I download the page and then I want to get a list of certain links. For building regular expressions, I use an app call The Regulator, which makes it pretty easy to build and test regular expressions. As a warning, I'm real weak with regular expressions. Let's say my regular expression is:
25
5169
by: Mike | last post by:
I have a regular expression (^(.+)(?=\s*).*\1 ) that results in matches. I would like to get what the actual regular expression is. In other words, when I apply ^(.+)(?=\s*).*\1 to " HEART (CONDUCTION DEFECT) 37.33/2 HEART (CONDUCTION DEFECT) WITH CATHETER 37.34/2 " the expression is "HEART (CONDUCTION DEFECT)". How do I gain access to the expression (not the matches) at runtime? Thanks, Mike
4
13962
by: Clodoaldo Pinto | last post by:
preg_match(): Compilation failed: regular expression too large at offset 0 The regular expression is 34,745 bytes long. <?php $regExp = 'huge regexp with 34,745 bytes'; echo '<pre>strlen($regExp) = ', strlen($regExp), "\n"; echo preg_match($regExp, 'sudokusweb.com'); echo '</pre>';
4
5689
by: mike | last post by:
how can I change the font color for an alternating row where the column data is formatted as a link? setting a style in the stylesheet for a { color:white; }
12
4867
by: ll | last post by:
I am trying to finalize a regular expression in javascript to only allow emails with a certain domain to be valid. Here is what I have so far: var emailFilter2=/\@aol.com/; if(!(emailFilter2.test(strng))) { error = "Please enter a valid email address with the AOL domain.\n \n"; }
3
2338
by: shapper | last post by:
Hello, I have a regular expression to validate email addresses: "\w+(\w+)*@\w+(\w+)*\.\w+(\w+)*" Now I need to force all emails to be from a given domain, for example, accept only: john@MyDomain.com andrew@MyDomain.com marysmith@MyDomain.com
0
9646
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
10346
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
10157
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...
0
9956
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
8982
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
7504
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
5386
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2887
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.