473,395 Members | 1,516 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.

template strings for matching?

Catching up on what's new in Python since I last used it a decade ago,
I've just been reading up on template strings. These are pretty
cool! However, just as a template string has some advantages over %
substitution for building a string, it seems like it would have
advantages over manually constructing a regex for string matching.

So... is there any way to use a template string for matching? I
expected something like:

templ = Template("The $object in $location falls mainly in the
$subloc.")
d = templ.match(s)

and then d would either by None (if s doesn't match), or a dictionary
with values for 'object', 'location', and 'subloc'.

But I couldn't find anything like that in the docs. Am I overlooking
something?

Thanks,
- Joe

Oct 9 '08 #1
2 1221
Joe Strout wrote:
Catching up on what's new in Python since I last used it a decade ago,
I've just been reading up on template strings. These are pretty
cool!
I don't think they've gained much traction and expect them to be superseded
by PEP 3101 (see http://www.python.org/dev/peps/pep-3101/ )
However, just as a template string has some advantages over %
substitution for building a string, it seems like it would have
advantages over manually constructing a regex for string matching.

So... is there any way to use a template string for matching? I
expected something like:

templ = Template("The $object in $location falls mainly in the
$subloc.")
d = templ.match(s)

and then d would either by None (if s doesn't match), or a dictionary
with values for 'object', 'location', and 'subloc'.

But I couldn't find anything like that in the docs. Am I overlooking
something?
I don't think so. Here's a DIY implementation:

import re

def _replace(match):
word = match.group(2)
if word == "$":
return "[$]"
return "(?P<%s>.*)" % word

def extract(template, text):
r = re.compile(r"([$]([$]|\w+))")
r = r.sub(_replace, template)
return re.compile(r).match(text).groupdict()
print extract("My $$ is on the $object in $location...",
"My $ is on the biggest bird in the highest tree...")

As always with regular expressions I may be missing some corner cases...

Peter
Oct 9 '08 #2
Pyparsing makes building expressions with named fields pretty easy.

from pyparsing import Word, alphas

wrd = Word(alphas)

templ = "The" + wrd("object") + "in" + wrd("location") + \
"stays mainly in the" + wrd("subloc") + "."

tests = """\
The rain in Spain stays mainly in the plain.
The snake in plane stays mainly in the cabin.
In Hempstead, Haverford and Hampshire hurricanes hardly ever
happen.
""".splitlines()
for t in tests:
t = t.strip()
try:
match = templ.parseString(t)
print match.object
print match.location
print match.subloc
print "Fields are: %(object)s %(location)s %(subloc)s" % match
except:
print "'" + t + "' is not a match."
print

Read more about pyparsing at http://pyparsing.wikispaces.com.
-- Paul

Oct 9 '08 #3

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

Similar topics

1
by: Joachim Spoerhase | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I am a XSLT-beginner and i read the XSLT-recommendation of the W3C through. But I did'nt really understand section 5.5 of the latest...
8
by: Bob | last post by:
I need to create a Regex to extract all strings (including quotations) from a C# or C++ source file. After being unsuccessful myself, I found this sample on the internet: ...
6
by: Neal | last post by:
Hi All, I used an article on XSLT and XML and creating a TOC written on the MSDN CodeCorner. ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033/dncodecorn/html/corner042699.htm However, it did'nt...
9
by: | last post by:
I am interested in scanning web pages for content of interest, and then auto-classifying that content. I have tables of metadata that I can use for the classification, e.g. : "John P. Jones" "Jane...
1
by: George2 | last post by:
Hello everyone, I am feeling template function is more tricky than template class. For the reason that the compiler will do the matching automatically for template function, but for template...
4
by: abir | last post by:
I am matching a template, and specializing based of a template, rather than a single class. The codes are like, template<template<typename T,typename Alloc = std::allocator<T> class pix{ }; ...
6
by: abir | last post by:
i have a template as shown template<typename Sclass Indexer{}; i want to have a specialization for std::vector both const & non const version. template<typename T,typename Aclass...
0
by: Robin Becker | last post by:
Joe Strout wrote: ........ you could use something like this to record the lookups .... def __new__(cls,*args,**kwds): .... self = dict.__new__(cls,*args,**kwds) .... self.__record =...
2
by: Bruce !C!+ | last post by:
as we known , we can use function pointer as: float Minus (float a, float b) { return a-b; } float (*getOp())(float, float) { return &Minus; } int main() { float (*opFun)(float, float) =...
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:
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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.