473,740 Members | 7,355 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Regex help...pretty please?

I'm trying to develop a little script that does some string
manipulation. I have some few hundred strings that currently look like
this:

cond(a,b,c)

and I want them to look like this:

cond(c,a,b)

but it gets a little more complicated because the conds themselves may
have conds within, like the following:

cond(0,cond(c,c ond(e,cond(g,h, (a<f)),(a<d)),( a<b)),(a<1))

What I want to do in this case is move the last parameter to the front
and then work backwards all the way out (if you're thinking recursion
too, I'm vindicated) so that it ends up looking like this:

cond((a<1), 0, cond((a<b),c,co nd((a<d), e, cond((a<f), g, h))))

futhermore, the conds may be multiplied by an expression, such as the
following:

cond(-1,1,f)*((float( e)*(2**4))+(flo at(d)*8)+(float (c)*4)+(float(b )*2)+float(a))

Here, all I want to do is switch the parameters of the conds without
touching the expression, like so:

cond(f,-1,1)*((float(e) *(2**4))+(float (d)*8)+(float(c )*4)+(float(b)* 2)+float(a))

So that's the gist of my problem statement. I immediately thought that
regular expressions would provide an elegant solution. I would go
through the string by conds, stripping them & the () off, until I got
to the lowest level, then move the parameters and work backwards. That
thought process became this:
-------------------------------------CODE--------------------------------------------------------
import re

def swap(left, middle, right):
left = left.replace("( ", "")
right = right.replace(" )", "")
temp = left
left = right
right = temp
temp = middle
middle = right
right = temp
whole = 'cond(' + left + ',' + middle + ',' + right + ')'
return whole

def condReplacer(st ring):
#regex = re.compile(r'co nd\(.*,.*,.+\)' )
regex = re.compile(r'co nd\(.*,.*,.+?\) ')
if not regex.search(st ring):
print "whole string is: " + string
[left, middle, right] = string.split(', ')
right = right.replace(' \'', ' ')
string = swap(left.strip (), middle.strip(), right.strip())
print "the new string is:" + string
return string
else:
more_conds = regex.search(st ring)
temp_string = more_conds.grou p()
firstParen = temp_string.fin d('(')
temp_string = temp_string[firstParen:]
print "there are more conditionals!" + temp_string
condReplacer(te mp_string)
def lineReader(file ):
for line in file:
regex = r'cond\(.*,.*,. +\)?'
if re.search(regex ,line,re.DOTALL ):
condReplacer(li ne)

if __name__ == "__main__":
input_file = open("only_cond s2.txt", 'r')
lineReader(inpu t_file)
-------------------------------------CODE--------------------------------------------------------

I think my problem lies in my regular expression... If I use the one
commented out I do a greedy search and in my test case where I have a
conditional * an expression, I grab the expression too, like so:

INPUT:

cond(-1,1,f)*((float( e)*(2**4))+(flo at(d)*8)+(float (c)*4)+(float(b )*2)+float(a))
OUTPUT:
whole string is:
(-1,1,f)*((float( e)*(2**4))+(flo at(d)*8)+(float (c)*4)+(float(b )*2)+float
(a))
the new string
is:cond(f*((flo at(e*(2**4+(flo at(d*8+(float(c *4+(float(b*2+f loat
(a,-1,1)

when all I really want to do is grab the part associated with the cond.
But if I do a non-greedy search I avoid that problem but stop too early
when I have an expression like this:

INPUT:
cond(a,b,(abs(c ) >= d))
OUTPUT:
whole string is: (a,b,(abs(c)
the new string is:cond((abs(c, a,b)

Can anyone help me with the regular expression? Is this even the best
approach to take? Anyone have any thoughts?

Thanks for your time!

Aug 23 '06 #1
4 1920
cond(a,b,c)
>
and I want them to look like this:

cond(c,a,b)

but it gets a little more complicated because the conds themselves may
have conds within, like the following:

cond(0,cond(c,c ond(e,cond(g,h, (a<f)),(a<d)),( a<b)),(a<1))
Regexps are *really* *REALLY* *bad* at arbitrarily nested
structures. really.

Sounds more like you want something like a lex/yacc sort of
solution. IIUC, pyparsing may do the trick for you. I'm not a
pyparsing wonk, but I can hold my own when it comes to crazy
regexps, and can tell you from experience that regexps are *not*
a good path to try and go down for this problem.

Many times, a regexp can be hammered into solving problems
superior solutions than employing regexps. This case is not even
one of those.

If you know the maximum depth of nesting you'll encounter, you
can do some hackish stunts to shoehorn regexps to solve the
problem. But if they are truely of arbitrary nesting-depth,
*good* *luck*! :)

-tkc


Aug 23 '06 #2
MooMaster wrote:
I'm trying to develop a little script that does some string
manipulation. I have some few hundred strings that currently look like
this:

cond(a,b,c)

and I want them to look like this:

cond(c,a,b)

but it gets a little more complicated because the conds themselves may
have conds within, like the following:

cond(0,cond(c,c ond(e,cond(g,h, (a<f)),(a<d)),( a<b)),(a<1))

What I want to do in this case is move the last parameter to the front
and then work backwards all the way out (if you're thinking recursion
too, I'm vindicated) so that it ends up looking like this:

cond((a<1), 0, cond((a<b),c,co nd((a<d), e, cond((a<f), g, h))))

futhermore, the conds may be multiplied by an expression, such as the
following:

cond(-1,1,f)*((float( e)*(2**4))+(flo at(d)*8)+(float (c)*4)+(float(b )*2)+float(a))

Here, all I want to do is switch the parameters of the conds without
touching the expression, like so:

cond(f,-1,1)*((float(e) *(2**4))+(float (d)*8)+(float(c )*4)+(float(b)* 2)+float(a))

So that's the gist of my problem statement. I immediately thought that
regular expressions would provide an elegant solution. I would go
through the string by conds, stripping them & the () off, until I got
to the lowest level, then move the parameters and work backwards. That
thought process became this:
-------------------------------------CODE--------------------------------------------------------
import re

def swap(left, middle, right):
left = left.replace("( ", "")
right = right.replace(" )", "")
temp = left
left = right
right = temp
temp = middle
middle = right
right = temp
whole = 'cond(' + left + ',' + middle + ',' + right + ')'
return whole

def condReplacer(st ring):
#regex = re.compile(r'co nd\(.*,.*,.+\)' )
regex = re.compile(r'co nd\(.*,.*,.+?\) ')
if not regex.search(st ring):
print "whole string is: " + string
[left, middle, right] = string.split(', ')
right = right.replace(' \'', ' ')
string = swap(left.strip (), middle.strip(), right.strip())
print "the new string is:" + string
return string
else:
more_conds = regex.search(st ring)
temp_string = more_conds.grou p()
firstParen = temp_string.fin d('(')
temp_string = temp_string[firstParen:]
print "there are more conditionals!" + temp_string
condReplacer(te mp_string)
def lineReader(file ):
for line in file:
regex = r'cond\(.*,.*,. +\)?'
if re.search(regex ,line,re.DOTALL ):
condReplacer(li ne)

if __name__ == "__main__":
input_file = open("only_cond s2.txt", 'r')
lineReader(inpu t_file)
-------------------------------------CODE--------------------------------------------------------

I think my problem lies in my regular expression... If I use the one
commented out I do a greedy search and in my test case where I have a
conditional * an expression, I grab the expression too, like so:

INPUT:

cond(-1,1,f)*((float( e)*(2**4))+(flo at(d)*8)+(float (c)*4)+(float(b )*2)+float(a))
OUTPUT:
whole string is:
(-1,1,f)*((float( e)*(2**4))+(flo at(d)*8)+(float (c)*4)+(float(b )*2)+float
(a))
the new string
is:cond(f*((flo at(e*(2**4+(flo at(d*8+(float(c *4+(float(b*2+f loat
(a,-1,1)

when all I really want to do is grab the part associated with the cond.
But if I do a non-greedy search I avoid that problem but stop too early
when I have an expression like this:

INPUT:
cond(a,b,(abs(c ) >= d))
OUTPUT:
whole string is: (a,b,(abs(c)
the new string is:cond((abs(c, a,b)

Can anyone help me with the regular expression? Is this even the best
approach to take? Anyone have any thoughts?

Thanks for your time!
You're gonna want a parser for this. pyparsing or spark would suffice.
However, since it looks like your source strings are valid python you
could get some traction out of the tokenize standard library module:

from tokenize import generate_tokens
from StringIO import StringIO

s =
'cond(-1,1,f)*((float( e)*(2**4))+(flo at(d)*8)+(float (c)*4)+(float(b )*2)+float(a))'

for t in generate_tokens (StringIO(s).re adline):
print t[1],
Prints:
cond ( - 1 , 1 , f ) * ( ( float ( e ) * ( 2 ** 4 ) ) + ( float ( d ) *
8 ) + ( float ( c ) * 4 ) + ( float ( b ) * 2 ) + float ( a ) )

Once you've got that far the rest should be easy. :)

Peace,
~Simon

http://pyparsing.wikispaces.com/
http://pages.cpsc.ucalgary.ca/~aycock/spark/
http://docs.python.org/lib/module-tokenize.html

Aug 23 '06 #3
"MooMaster" <nt*****@gmail. comwrote in message
news:11******** **************@ 74g2000cwt.goog legroups.com...
I'm trying to develop a little script that does some string
manipulation. I have some few hundred strings that currently look like
this:

cond(a,b,c)

and I want them to look like this:

cond(c,a,b)
<snip>

Pyparsing makes this a fairly tractable problem. The hardest part is
defining the valid contents of a relational and arithmetic expression, which
may be found within the arguments of your cond(a,b,c) constructs.

Not guaranteeing this 100%, but it did convert your pathologically nested
example on the first try.

-- Paul

----------
from pyparsing import *

ident = ~Literal("cond" ) + Word(alphas)
number = Combine(Optiona l("-") + Word(nums) + Optional("." + Word(nums)))

arithExpr = Forward()
funcCall = ident+"("+delim itedList(arithE xpr)+")"
operand = number | funcCall | ident
binop = oneOf("+ - * /")
arithExpr << ( ( operand + ZeroOrMore( binop + operand ) ) | ("(" +
arithExpr + ")" ) )
relop = oneOf("< == <= >= != <>")

condDef = Forward()
simpleCondExpr = arithExpr + ZeroOrMore( relop + arithExpr ) | condDef
multCondExpr = simpleCondExpr + "*" + arithExpr
condExpr = Forward()
condExpr << ( simpleCondExpr | multCondExpr | "(" + condExpr + ")" )

def reorderArgs(t):
return "cond(" + ",".join(["".join(t.arg3) , "".join(t.arg1) ,
"".join(t.a rg2)]) + ")"

condDef << ( Literal("cond") + "(" + Group(condExpr) .setResultsName ("arg1")
+ "," +
Group(condExpr) .setResultsName ("arg2")
+ "," +
Group(condExpr) .setResultsName ("arg3")
+ ")" ).setParseActio n( reorderArgs )

tests = [
"cond(a,b,c )",
"cond(1>2,b,c)" ,
"cond(-1,1,f)*((float( e)*(2**4))+(flo at(d)*8)+(float (c)*4)+(float(b )*2)+floa
t(a))",
"cond(a,b,(abs( c) >= d))",
"cond(0,cond(c, cond(e,cond(g,h ,(a<f)),(a<d)), (a<b)),(a<1))",
]

for t in tests:
print t,"->",condExpr.tra nsformString(t)
----------
Prints:
cond(a,b,c) -cond(c,a,b)
cond(1>2,b,c) -cond(c,1>2,b)
cond(-1,1,f)*((float( e)*(2**4))+(flo at(d)*8)+(float (c)*4)+(float(b )*2)+float
(a)) ->
cond(f,-1,1)*((float(e) *(2**4))+(float (d)*8)+(float(c )*4)+(float(b)* 2)+float
(a))
cond(a,b,(abs(c ) >= d)) -cond((abs(c)>=d ),a,b)
cond(0,cond(c,c ond(e,cond(g,h, (a<f)),(a<d)),( a<b)),(a<1)) ->
cond((a<1),0,co nd((a<b),c,cond ((a<d),e,cond(( a<f),g,h))))
Aug 24 '06 #4
MooMaster Wrote:
I'm trying to develop a little script that does some string
manipulation. I have some few hundred strings that currently look like
this:
cond(a,b,c)
and I want them to look like this:
cond(c,a,b)
I zoned out on your question and created a very simple flipper.
Although it will not solve your problem maybe someone looking for a
simpler version may find it useful as a starting point. I hope it
proves useful. I'll post my simple flipper here:

s = 'cond(1,savv(gr ave(3,2,1),y,x) ,maxx(c,b,a),0) '
def argFlipper(s):
''' take a string of arguments and reverse'em e.g.
>>cond(1,savv(g rave(3,2,1),y,x ),maxx(c,b,a),0 )
-cond(0,maxx(a,b ,c),savv(x,y,gr ave(1,2,3)),1)

'''

count = 0
keyholder = {}
while 1:
if s.find('(') 0:
count += 1
value = '%sph' + '%d' % count
tempstring = [x for x in s]
startindex = s.rfind('(')
limitindex = s.find(')', startindex)
argtarget = s[startindex + 1:limitindex].split(',')
argreversed = ','.join(revers ed(argtarget))
keyholder[value] = '(' + argreversed + ')'
tempstring[startindex:limi tindex + 1] = value
s = ''.join(tempstr ing)
else:
while count and keyholder:
s = s.replace(value , keyholder[value])
count -= 1
value = '%sph' + '%d' % count
return s

print argFlipper(s)

Aug 24 '06 #5

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

Similar topics

4
9763
by: aevans1108 | last post by:
expanding this message to microsoft.public.dotnet.xml Greetings Please direct me to the right group if this is an inappropriate place to post this question. Thanks. I want to format a numeric value according to an arbitrary regular expression.
7
1912
by: Razzie | last post by:
Hey all, Decided to give a shot at Regular expressions - need a bit of help :) I can't seem to find the right regex for matching words like "*test*" or *somevalue*" - in short, all words starting and ending with a *. I tried things like string regex = @"(^*\|*^)"); but it still doesn't work completely (matches on "*test" too for example). If anything could help me with this, that would be appreciated.
6
4799
by: Dave | last post by:
I'm struggling with something that should be fairly simple. I just don't know the regext syntax very well, unfortunately. I'd like to parse words out of what is basically a boolean search string. It's actually the input string into a Microsoft Index Server search. The string will consist of words, perhaps enclosed in quotes or parentheses. I'd like to use Regex to pull out the words, or the phrases if the words are enclosed in quotes....
4
2663
by: Friday | last post by:
Being an Old L.A.M.P guy, I beg you to please excuse my ignorance of dot.net (and all things Windows, for that matter). As part of an experiment (to learn enough ASP/VB.net to port a series of existing PHP scripts of mine to work on IIS), I have created the following simple function to compare a Website visitor's IP address against a varabe-array. The experiment invovleas a common scenario -- banning a Website visitor by IP Address: ...
17
3979
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/
9
2085
by: jmchadha | last post by:
I have got the following html: "something in html ... etc.. city1... etc... <a class="font1" href="city1.html" onclick="etc."click for <b>info</bon city1 </a> ... some html. city1.. can repeat lot of times here.... Requirement: ------------------- I want to get the value of "href" i.e "city1.html" by searching "city1" between the <a</atag. Please note that "city1" can repeat lot of
4
3705
by: .... | last post by:
Hi I'm trying to do something which I think is pretty simple, but really I don't know what I'm doing :-) I have a string like this HELLO WORLD 25 ERRORS
7
2588
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
3
4872
by: =?Utf-8?B?TmF2ZWVu?= | last post by:
Not sure if this is the right forum for this question but couldn'd find another newsgroup. I am new to Regular expressions and would like help in deciding which pattern allows me to split a string into sets of words based on capital letter. For e.g. if i have a string "FirstnameLastname" I would like the result to return me Firstname and Lastname. The other conditions of the input string are 1) If whitespace exists, do not return a...
0
8969
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
9484
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
9342
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9272
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9211
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...
0
8218
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6756
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...
1
3286
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
2
2748
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.