Hello,
I would like to create a set of very similar regular expression. In
my initial thought, I'd hoped to create a regular expression with a
variable inside of it that I could simply pass a string into by
defining this variable elsewhere in my module/function/class where I
compile the regular expression, thus making for an easy substitution.
However, still after JFGI'ing, I still cannot find the syntax to place
a variable inside a regular expression in Python. Is such a thing
possible, and if so what is the syntax to do it? If this is not
possible, what would be the Python way of swapping a small part of the
insides of a regexp without having to copy and paste the code to create
as many variations as necessary?
To make this more concrete, I think an example is in order. Let's say
I have a document like this
The Beatles
Rubber Soul
Track Listings
1. Drive My Car
2. Norwegian Wood (This Bird Has Flown)
3. You Won't See Me
4. Nowhere Man
5. Think for Yourself
6. Word
7. Michelle
8. What Goes On
9. Girl
10. I'm Looking Through You
11. In My Life
12. Wait
13. If I Needed Someone
14. Run for Your Life
Original Release Date: December 3, 1965
Number of Discs: 1
Label: Capitol
....
and I want to look for tracks that contain 'oo'. Then, maybe later, I
want to look for 'ee', or maybe 'ou'. All the regular expressions would
start by searching for a digit at the beginning of the line, and they
would allow for characters up until the desired two-letter vowel
combination, and then search for the two-letter vowel combination. How
can I provide for a way to "drop-in" the two-letter combination I want?
Thanks very much for your help and assistance in advance.
Chris 6 8281
Chris Lasher wrote: I would like to create a set of very similar regular expression. In my initial thought, I'd hoped to create a regular expression with a variable inside of it that I could simply pass a string into by defining this variable elsewhere in my module/function/class where I compile the regular expression, thus making for an easy substitution.
Can you use the %-formatting operations? This is what I normally do
with a situation like this. It means you have to compile a new regular
expression for each different value you substitute into the expression,
but that's to be expected anyway when you're trying to check several
different regular expressions... import re s = """\
.... 1. Drive My Car
.... 2. Norwegian Wood (This Bird Has Flown)
.... 3. You Won't See Me
.... 4. Nowhere Man
.... 5. Think for Yourself
.... 6. Word
.... 7. Michelle
.... 8. What Goes On
.... 9. Girl
.... 10. I'm Looking Through You
.... 11. In My Life
.... 12. Wait
.... 13. If I Needed Someone
.... 14. Run for Your Life""" expr = r'(\w*%s\w*)' re.compile(expr % r'oo').findall( s)
['Wood', 'Looking'] re.compile(expr % r'ou').findall( s)
['You', 'Yourself', 'Through', 'You', 'Your']
Steve
Thanks for the reply, Steve! That ought to work quite nicely! For some
reason, I hadn't thought of using %-formatting. I probably should have,
but I'm still learning Python and re-learning programming in general.
This helps a lot, so thanks again.
Chris
On Fri, 2004-12-10 at 05:51, Chris Lasher wrote: Thanks for the reply, Steve! That ought to work quite nicely! For some reason, I hadn't thought of using %-formatting. I probably should have, but I'm still learning Python and re-learning programming in general. This helps a lot, so thanks again.
Just be careful, when doing this, that your inserted text is also a
regular expression part. You don't want to do this:
re.compile(r'%s made (\d{1,4}.\d{2}) ' % "J. Smith"
because you'll match "JB Smith made 24.21" etc as well. You could also
end up inserting ?s , *s etc, resulting in some rather frustrating bugs.
--
Craig Ringer
Robert, Craig, thanks for your replies. I'll only be dealing with
alphanumerics for this project, I think, but it's good to be aware of
this possible problem for later projects. The re.escape(...) is a handy
method to know about. Thanks very much.
On Thursday 09 December 2004 03:51 pm, Chris Lasher wrote: Thanks for the reply, Steve! That ought to work quite nicely! For some reason, I hadn't thought of using %-formatting. I probably should have, but I'm still learning Python and re-learning programming in general. This helps a lot, so thanks again.
Remember, in Python, a regex (well, regex source) is just a string, so
you can do any string manipulation you want to with it, and python has
a lot of tools for doing that.
One cool way to make regexes more readable, that i've seen proposed,
is to break them into components like the following (please pardon my
lack of regex skill, these may not actually work , but you get the idea):
normalword = r'[A-Za-z][a-z]*'
digit = r'\d'
capletter = r'[A-Z]'
codeblock = normalword + 4*digit + '-' + 3*digit + 2*capletter + '\s+' + normalword
or somesuch (the 'r' BTW stands for 'raw', not 'regex', and while it's the most
obvious use, there's nothing particularly special about r strings, except for
not trying to process escape characters, thus avoiding the "pile of toothpicks"
problem).
And hey, you could probably use a regex to modify a regex, if you were
really twisted. ;-)
Sorry. I really shouldn't have said that. Somebody's going to do it now. :-P
Cheers,
Terry
--
Terry Hancock ( hancock at anansispacework s.com )
Anansi Spaceworks http://www.anansispaceworks.com
Terry Hancock wrote: And hey, you could probably use a regex to modify a regex, if you were really twisted. ;-)
Sorry. I really shouldn't have said that. Somebody's going to do it now. :-P
Sure, but only 'cause you asked so nicely. =) import re def internationaliz e(expr,
.... letter_matcher= re.compile(r'\[A-(?:Za-)?z\]')):
.... return letter_matcher. sub(r'[^\W_\d]', expr)
.... def compare(expr, text):
.... def item_str(matche r):
.... return ' '.join(matcher. findall(text))
.... print 'reg: ', item_str(re.com pile(expr))
.... print 'intl:', item_str(re.com pile(internatio nalize(expr),
.... re.UNICODE))
.... compare(r'\d+\s +([A-z]+)', '1 viola. 2 voilà')
reg: viola voil
intl: viola voilà compare(r'\d+\s +([A-Za-z]+)', '1 viola. 2 voilà')
reg: viola voil
intl: viola voilà
This code converts [A-z] style regexps to a regexp that is suitable for
use with other encodings. Note that without the conversion, characters
like 'à' are not found.
Steve This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Kenneth McDonald |
last post by:
I'm working on the 0.8 release of my 'rex' module, and would appreciate
feedback, suggestions, and criticism as I work towards finalizing the
API and feature sets. rex is a module intended to make regular expressions
easier to create and use (and in my experience as a regular expression
user, it makes them MUCH easier to create and use.)
...
|
by: ajitgoel |
last post by:
Hi;
I need some simple help with my regular expressions.
I want to search my input text for all the boolean variables which do
not start with bln. i.e I want to match "bool followed by 1 or more
spaces followed by text other than bln" in my input text.
Eg:
1. private bool dispose; should be highlighted
2. private bool blndispose;...
|
by: Dooglo |
last post by:
I'm new VB and programming all together, but I'm getting he hang of it.
My question is;
I'm writting a program to figure square feet and yards when the user inputs
"Length in feet and inch ( seperate boxes), Width in feet and inches
(seperate boxes), and thickness in feet and inches (all so in seperate
boxes). I haven't quit figured out...
|
by: norton |
last post by:
Hello,
Does any one know how to extact the following text into 4 different
groups(namely Date, Artist, Album and Quality)?
- Artist - Album
Artist - Album
- Artist - Album
- Artist - Album-
i have try this syntax but it failed
|
by: Billa |
last post by:
Hi,
I am replaceing a big string using different regular expressions (see
some example at the end of the message). The problem is whenever I
apply a "replace" it makes a new copy of string and I want to avoid
that. My question here is if there is a way to pass either a memory
stream or array of "find", "replace" expressions or any other way...
| |
by: a |
last post by:
I'm a newbie needing to use some Regular Expressions in PHP.
Can I safely use the results of my tests using 'The Regex Coach'
(http://www.weitz.de/regex-coach/index.html)
Are the Regular Expressions used in Perl identical to the Regular
Expressions in PHP?
|
by: Daniel |
last post by:
Is it possible to use regular expressions inside of an xpath statement
executed by System.Xml.XmlDocument.SelectSingleNode() ?
string sdoc = "<foo><bar a='1'/><bar a='2'/></foo>";
System.Xml.XmlDocument pdoc = new System.Xml.XmlDocument();
pdoc.LoadXml(sdoc);
System.Xml.XmlNode pnode =
pdoc.SelectSingleNode("//foo/bar/matches(.,'\\d')");...
|
by: Allan Ebdrup |
last post by:
I have a dynamic list of regular expressions, the expressions don't change
very often but they can change. And I have a single string that I want to
match the regular expressions against and find the first regular expression
that matches the string.
I've gor the regular expressions ordered so that the highest priority is
first (if two or more...
|
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...
|
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...
|
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. ...
| |
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...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |