473,395 Members | 1,412 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Possible to insert variables into regular expressions?

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

Jul 18 '05 #1
6 8273
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
Jul 18 '05 #2
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

Jul 18 '05 #3
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

Jul 18 '05 #4
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.

Jul 18 '05 #5
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 anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 18 '05 #6
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 internationalize(expr, .... letter_matcher=re.compile(r'\[A-(?:Za-)?z\]')):
.... return letter_matcher.sub(r'[^\W_\d]', expr)
.... def compare(expr, text): .... def item_str(matcher):
.... return ' '.join(matcher.findall(text))
.... print 'reg: ', item_str(re.compile(expr))
.... print 'intl:', item_str(re.compile(internationalize(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
Jul 18 '05 #7

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

Similar topics

1
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...
2
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...
42
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 (...
7
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 -...
7
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...
3
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...
4
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>";...
1
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...

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.