473,769 Members | 6,120 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1245
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(templat e, text):
r = re.compile(r"([$]([$]|\w+))")
r = r.sub(_replace, template)
return re.compile(r).m atch(text).grou pdict()
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.parseStri ng(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
2348
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 specification. The Problem is what template rule to be used if there are more than one matching template rule. You will find the following:
8
2590
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: @"@?""""|@?"".*?(?!\\).""|''|'.*?(?!\\).'" I am inputting the entire source file string and using it with RegexOptions.Singleline. This works OK with, unless the string ends with a back-slash. For example: "This is a test\\". Can anybody see how to fix this...
6
1831
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 quite answer all my questions. How would one create a 3 level TOC when each item level / node was differently named (They used Template match and for-each, but the template match worked as on a 3 level structure they usedf the same named xml...
9
2682
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 T. Smith" "Fred Barzowsky" "Department of Oncology" "Office of Student Affairs" "Lewis Hall" etc. etc. etc. I am wondering what the efficient way to do this in code might be. The dumb and brute-force way would be to loop through the content...
1
1227
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 class, developer can assign how to match. Sometimes compiler is doing mysterious matching rules for template function, which makes us confused. Does anyone have the same
4
2062
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{ }; template<> class pix<vector>{
6
2618
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 Indexer<std::vector<T,A {} matches only with nonconst version. anyway to match it for both? and get if it is const or nonconst? Actually i want 2 specialization, one for std::vector<T,Aconst & non const other for std::deque<T,Aconst & non const.
0
207
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 = set() .... return self .... def _record_clear(self):
2
465
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) = NULL; opFun= getOp();
0
9590
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
9424
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10223
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
9866
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...
1
7413
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
5310
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3968
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
3
2815
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.