use a regex or not? | Bytes (2024)

Joost Jacob

I am looking for a function that takes an input string
and a pattern, and outputs a dictionary.

# @param s str, lowercase letters
# @param p str, lowercase and uppercase letters
# @return dict
def fill(s, p):
d = {}
....
return d

String s has characters from the lowercase letters.
String p is a pattern, a string of characters from the
lowercase and uppercase letters. The idea is to match
s with p, where lowercase letters have to match
exactly, and to fill variables (with an uppercase
letter name) with the rest of s. The variables are
collected in a dictionary with the resulting bindings.
A variable that occurs in more than one place in p must
bind to the same substring of s.

Tests:

fill('ab', p='aA'){'A': 'b'} fill('ab', p='Ab'){'A': 'a'} fill('bb', p='Ab') # no match{} fill('aa', p='Aa'){'A': 'a'} fill('aa', p='Ab') # no match{} fill('abb', p='aA'){'A': 'bb'} fill('aba', p='aAa'){'A': 'b'} fill('abb', p='aAa') # no match{} fill('abab', p='aAaA') # A-matches must be equal{'A': 'b'} fill('abac', p='aAaA') # no match{} fill('abac', p='aAaB')

{'A': 'b', 'B': 'c'}

Can you do it? Is trying a solution with a regex a
good idea?

Jul 19 '05 #1

Subscribe Reply

3 use a regex or not? | Bytes (1) 1231 use a regex or not? | Bytes (2)

Joost Jacob

Oops, the 3rd test should be

fill('bb', p='Aa')

resulting in the empty dict {} because no binding for A can be found.

Jul 19 '05 #2

Kent Johnson

Joost Jacob wrote:

I am looking for a function that takes an input string
and a pattern, and outputs a dictionary.

Here is one way. I won't say it's pretty but it is fairly straightforward and it passes all your tests.

Kent

def fill(s, p):
"""

fill('ab', p='aA'){'A': 'b'}
fill('ab', p='Ab'){'A': 'a'}
fill('bb', p='Aa') # no match{}
fill('aa', p='Aa'){'A': 'a'}
fill('aa', p='Ab') # no match{}
fill('abb', p='aA'){'A': 'bb'}
fill('aba', p='aAa'){'A': 'b'}
fill('abb', p='aAa') # no match{}
fill('abab', p='aAaA') # A-matches must be equal{'A': 'b'}
fill('abac', p='aAaA') # no match{}
fill('abac', p='aAaB')

{'A': 'b', 'B': 'c'}
"""

# If s is longer than p the extra chars of s become part of the
# last item of s
if len(s) > len(p):
ss = list(s[:len(p)])
ss[-1] = ss[-1] + s[len(p):]
s = ss

d = {}
seen = {}

for s1, p1 in zip(s, p):
# Lower case have to map to themselves
if p1.islower() and s1 != p1:
# print 'Non-identity map for %s: %s' % (p1, s1)
return {}

try:
# Check for multiple mappings from p1
old_s = d[p1]

if old_s != s1:
# We saw this s before but the mapping is different
return {}

# We saw this s1, p1 before with the same mapping
continue

except KeyError:
# Check for multiple mappings to p1
if seen.get(s1, p1.lower()) != p1.lower():
return {}

# This is a new mapping
d[p1] = s1
seen[s1] = p1.lower()
# Strip out the lower case mappings
return dict((k, v) for k, v in d.iteritems() if k.isupper())

def _test():
import doctest
doctest.testmod ()

if __name__ == "__main__":
_test()

Jul 19 '05 #3

Paul McGuire

Here's a hybrid solution, using pyparsing to parse your input pattern
string (p), and transforming it into a regexp string. Then uses
re.match using the regexp to process string (s), and then builds a
dictionary from the matched groups.

Download pyparsing at http://pyparsing.sourceforge.net.

-- Paul

=============== ====
import re
from pyparsing import Word,OneOrMore

previousKeys = []
def createUpperKey( s,l,t):
if t[0] not in previousKeys:
ret = "(?P<%s>.*) " % t[0]
previousKeys.ap pend(t[0])
else:
ret = "(?P=%s)" % t[0]
return ret

lowers = "abcdefghijklmn opqrstuvwxyz"
uppers = lowers.upper()
lowerLetter = Word(lowers,max =1)
upperLetter = Word(uppers,max =1).setParseAct ion(createUpper Key)
pattern = OneOrMore( lowerLetter | upperLetter )

def fill(s,p):
# reset keys found in p-patterns
del previousKeys[:]

# create regexp by running pyparsing transform
regexp = pattern.transfo rmString(p) + "$"

# create dict from re-matched groups
match = re.match(regexp ,s)
if match:
ret = dict( [ (k,match.group( k)) for k in previousKeys ] )
else:
ret = dict()
return ret

tests = [
('ab','aA'),
('ab','Ab'),
('bb','Aa'),
('aa','Aa'),
('aa','Ab'),
('abb','aA'),
('aba','aAa'),
('abbba','aAa') ,
('abbbaba','aAa '),
('abb','aAa'),
('abab','aAaA') ,
('abac','aAaA') ,
('abac','aAaB') ,
]

for t in tests:
print t,fill( *t )

=============== =
Gives:
('ab', 'aA') {'A': 'b'}
('ab', 'Ab') {'A': 'a'}
('bb', 'Aa') {}
('aa', 'Aa') {'A': 'a'}
('aa', 'Ab') {}
('abb', 'aA') {'A': 'bb'}
('aba', 'aAa') {'A': 'b'}
('abbba', 'aAa') {'A': 'bbb'}
('abbbaba', 'aAa') {'A': 'bbbab'}
('abb', 'aAa') {}
('abab', 'aAaA') {'A': 'b'}
('abac', 'aAaA') {}
('abac', 'aAaB') {'A': 'b', 'B': 'c'}

Jul 19 '05 #4

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

Similar topics

3 2066

Translating JavaScript function with Regex to CSharp

by: Jon Maz |last post by:

Hi All, Am getting frustrated trying to port the following (pretty simple) function to CSharp. The problem is that I'm lousy at Regular Expressions.... //from http://support.microsoft.com/default.aspx?scid=kb;EN-US;246800 function fxnParseIt() { var sInputString = 'asp and database';

.NET Framework

9 4565

How can I do this without Regex ?

by: Tim Conner |last post by:

Is there a way to write a faster function ? public static bool IsNumber( char Value ) { if (Regex.IsMatch( Value.ToString(), @"^+$" )) { return true; } else return false; }

C# / C Sharp

20 8046

Regex - Memory performance

by: jeevankodali |last post by:

Hi I have an .Net application which processes thousands of Xml nodes each day and for each node I am using around 30-40 Regex matches to see if they satisfy some conditions are not. These Regex matches are called within a loop (like if or for). E.g. for(int i = 0; i < 10; i++) { Regex r = new Regex();

C# / C Sharp

17 3947

Which RegEx Testing Tool Do You Prefer?

by: clintonG |last post by:

I'm using an .aspx tool I found at but as nice as the interface is I think I need to consider using others. Some can generate C# I understand. Your preferences please... <%= Clinton Gallagher http://forta.com/books/0672325667/

ASP.NET

6 2488

How to get rid of the regex????

by: Extremest |last post by:

I have a huge regex setup going on. If I don't do each one by itself instead of all in one it won't work for. Also would like to know if there is a faster way tried to use string.replace with all the right parts in there in one big line and for some reason that did not work either. Here is my regex's. static Regex rar = new...

C# / C Sharp

7 2569

Quick regex question

by: Extremest |last post by:

I am using this regex. static Regex paranthesis = new Regex("(\\d*/\\d*)", RegexOptions.IgnoreCase); it should find everything between parenthesis that have some numbers onyl then a forward slash then some numbers. For some reason I am not getting that. It won't work at all in 2.0

C# / C Sharp

3 2692

A nice way to use regex for complicate parsing

by: aspineux |last post by:

My goal is to write a parser for these imaginary string from the SMTP protocol, regarding RFC 821 and 1869. I'm a little flexible with the BNF from these RFC :-) Any comment ? tests= def RN(name, regex): """protect using () and give an optional name to a regex""" if name:

Python

15 50167

Regex to remove \t \r \n from string

by: morleyc |last post by:

Hi, i would like to remove a number of characters from my string (\t \r \n which are throughout the string), i know regex can do this but i have no idea how. Any pointers much appreciated. Chris

C# / C Sharp

4 2663

Parsing in between strings using Regex

by: CJ |last post by:

Is this the format to parse a string and return the value between the item? Regex pRE = new Regex("<File_Name>.*>(?<insideText>.*)</File_Name>"); I am trying to parse this string. <File_Name>Services</File_Name> Thanks

C# / C Sharp

1725

Regex woes

by: Karch |last post by:

I have these two methods that are chewing up a ton of CPU time in my application. Does anyone have any suggestions on how to optimize them or rewrite them without Regex? The most time-consuming operation by a long-shot is the regex.Replace. Basically the only purpose of it is to remove spaces between opening/closing tags and the element name....

C# / C Sharp

7546

What is ONU?

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...

General

7471

Changing the language in Windows 10

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...

Windows Server

7740

Problem With Comparison Operator <=> in G++

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. ...

C / C++

7985

Maximizing Business Potential: The Nexus of Website Design and Digital Marketing

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...

Online Marketing

7830

Discussion: How does Zigbee compare with other wireless protocols in smart home applications?

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...

General

3496

Windows Forms - .Net 8.0

by: adsilva |last post by:

A Windows Forms form does not have the event Unload, like VB6. What one acts like?

Visual Basic .NET

1 1962

transfer the data from one system to another through ip address

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

C# / C Sharp

1 1082

How to add payments to a PHP MySQL app.

by: muto222 |last post by:

How can i add a mobile payment intergratation into php mysql website.

PHP

784

Comprehensive Guide to Website Development in Toronto: Expert Insights from BSMN Consultancy

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...

General

use a regex or not? | Bytes (2024)
Top Articles
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 5918

Rating: 4.8 / 5 (48 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.