473,769 Members | 1,805 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Breaking up Strings correctly:

Hello:

I have been searching for an easy solution, and hopefully one
has already been written, so I don't want to reinvent the wheel:

Suppose I have a string of expressions such as:
"((($IP = "127.1.2.3" ) AND ($AX < 15)) OR (($IP = "127.1.2.4" ) AND ($AY !=
0)))
I would like to split up into something like:
[ "OR",
"(($IP = "127.1.2.3" ) AND ($AX < 15))",
"(($IP = "127.1.2.4" ) AND ($AY != 0))" ]

which I may then decide to or not to further split into:
[ "OR",
["AND", "($IP = "127.1.2.3" )", "($AX < 15)"],
["AND", "(($IP = "127.1.2.4" )", ($AY != 0))"] ]

Is there an easy way to do this?
I tried using regular expressions, re, but I don't think it is
recursive enough. I really want to break it up from:
(E1 AND_or_OR E2) and make that int [AND_or_OR, E1, E2]
and apply the same to E1 and E2 recursively until E1[0] != '('

But the main problem I am running to is, how do I split this up
by outer parentheseis. So that I get the proper '(' and ')' to split
this upper correctly?
Thanks in advance:
Michael Yanowitz
Apr 9 '07 #1
5 1482
On Apr 9, 7:19 am, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
Hello:

I have been searching for an easy solution, and hopefully one
has already been written, so I don't want to reinvent the wheel:

Suppose I have a string of expressions such as:
"((($IP = "127.1.2.3" ) AND ($AX < 15)) OR (($IP = "127.1.2.4" ) AND ($AY !=
0)))
I would like to split up into something like:
[ "OR",
"(($IP = "127.1.2.3" ) AND ($AX < 15))",
"(($IP = "127.1.2.4" ) AND ($AY != 0))" ]

which I may then decide to or not to further split into:
[ "OR",
["AND", "($IP = "127.1.2.3" )", "($AX < 15)"],
["AND", "(($IP = "127.1.2.4" )", ($AY != 0))"] ]

Is there an easy way to do this?
I tried using regular expressions, re, but I don't think it is
recursive enough. I really want to break it up from:
(E1 AND_or_OR E2) and make that int [AND_or_OR, E1, E2]
and apply the same to E1 and E2 recursively until E1[0] != '('

But the main problem I am running to is, how do I split this up
by outer parentheseis. So that I get the proper '(' and ')' to split
this upper correctly?

Thanks in advance:
Michael Yanowitz
This problem is right down the pyparsing fairway! Pyparsing is a
module for defining recursive-descent parsers, and it has some built-
in help just for applications such as this.

You start by defining the basic elements of the text to be parsed. In
your sample text, you are combining a number of relational
comparisons, made up of variable names and literal integers and quoted
strings. Using pyparsing classes, we define these:

varName = Word("$",alphas , min=2)
integer = Word("012345678 9").setParseAct ion( lambda t : int(t[0]) )
varVal = dblQuotedString | integer

varName is a "word" starting with a $, followed by 1 or more alphas.
integer is a "word" made up of 1 or more digits, and we add a parsing
action to convert these to Python ints. varVal shows that a value can
be an integer or a dblQuotedString (a common expression included with
pyparsing).

Next we define the set of relational operators, and the comparison
expression:

relationalOp = oneOf("= < = <= !=")
comparison = Group(varName + relationalOp + varVal)

The comparison expression is grouped so as to keep tokens separate
from surrounding expressions.

Now the most complicated part, to use the operatorPrecede nce method
from pyparsing. It is possible to create the recursive grammar
explicitly, but this is another application that is very common, so
pyparsing includes a helper for it too. Here is your set of
operations defined using operatorPrecede nce:

boolExpr = operatorPrecede nce( comparison,
[
( "AND", 2, opAssoc.LEFT ),
( "OR", 2, opAssoc.LEFT ),
])

operatorPrecede nce takes 2 arguments: the base-level or atom
expression (in your case, the comparison expression), and a list of
tuples listing the operators in descending priority. Each tuple gives
the operator, the number of operands (1 or 2), and whether it is right
or left associative.

Now the only thing left to do is use boolExpr to parse your test
string:

results = boolExpr.parseS tring('((($IP = "127.1.2.3" ) AND ($AX < 15))
OR (($IP = "127.1.2.4" ) AND ($AY != 0)))')

pyparsing returns parsed tokens as a rich object of type
ParseResults. This object can be accessed as a list, dict, or object
instance with named attributes. For this example, we'll actually
create a nested list using ParseResults' asList method. Passing this
list to the pprint module we get:

pprint.pprint( results.asList( ) )

prints

[[[['$IP', '=', '"127.1.2.3" '], 'AND', ['$AX', '<', 15]],
'OR',
[['$IP', '=', '"127.1.2.4" '], 'AND', ['$AY', '!=', 0]]]]
Here is the whole program in one chunk (I also added support for NOT -
higher priority than AND, and right-associative):

test = '((($IP = "127.1.2.3" ) AND ($AX < 15)) OR (($IP = "127.1.2.4" )
AND ($AY != 0)))'

from pyparsing import oneOf, Word, alphas, dblQuotedString , nums, \
Literal, Group, operatorPrecede nce, opAssoc

varName = Word("$",alphas )
integer = Word(nums).setP arseAction( lambda t : int(t[0]) )
varVal = dblQuotedString | integer

relationalOp = oneOf("= < = <= !=")
comparison = Group(varName + relationalOp + varVal)

boolExpr = operatorPrecede nce( comparison,
[
( "NOT", 1, opAssoc.RIGHT ),
( "AND", 2, opAssoc.LEFT ),
( "OR", 2, opAssoc.LEFT ),
])

import pprint
pprint.pprint( boolExpr.parseS tring(test).asL ist() )
The pyparsing wiki includes some related examples, SimpleBool.py and
SimpleArith.py - go to http://pyparsing.wikispaces.com/Examples.

-- Paul

Apr 9 '07 #2
On Apr 9, 1:19 pm, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
Hello:

I have been searching for an easy solution, and hopefully one
has already been written, so I don't want to reinvent the wheel:

Suppose I have a string of expressions such as:
"((($IP = "127.1.2.3" ) AND ($AX < 15)) OR (($IP = "127.1.2.4" ) AND ($AY !=
0)))
I would like to split up into something like:
[ "OR",
"(($IP = "127.1.2.3" ) AND ($AX < 15))",
"(($IP = "127.1.2.4" ) AND ($AY != 0))" ]

which I may then decide to or not to further split into:
[ "OR",
["AND", "($IP = "127.1.2.3" )", "($AX < 15)"],
["AND", "(($IP = "127.1.2.4" )", ($AY != 0))"] ]

Is there an easy way to do this?
If you look into infix to prefix conversion algorithms it might help
you. The following seems to work with the example you give, but not
tested further:
data = '''
((($IP = "127.1.2.3" ) AND ($AX < 15)) OR (($IP = "127.1.2.4" ) AND
($AY !=
0)))
'''

import tokenize
from cStringIO import StringIO

opstack = []
valstack = []
s = ''
g = tokenize.genera te_tokens(Strin gIO(data).readl ine) # tokenize the
string
for _, tokval, _, _, _ in g:
if tokval in ['(', ')', 'AND', 'OR']:
if tokval != ')':
opstack.append( tokval)
else:
if s:
valstack.append (s)
s = ''
while opstack[-1] != '(':
op = opstack.pop()
rhs = valstack.pop()
lhs = valstack.pop()
valstack.append ([op, lhs, rhs])
opstack.pop()
else:
s += tokval.strip()

print valstack

[['OR', ['AND', '$IP="127.1.2.3 "', '$AX<15'], ['AND',
'$IP="127.1.2.4 "', '$AY!=0']]]

Gerard

Apr 9 '07 #3
En Mon, 09 Apr 2007 12:39:44 -0300, Paul McGuire <pt***@austin.r r.com>
escribió:
On Apr 9, 7:19 am, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
>>
Suppose I have a string of expressions such as:
"((($IP = "127.1.2.3" ) AND ($AX < 15)) OR (($IP = "127.1.2.4" ) AND ($AY
!=
0)))
I would like to split up into something like:

[ "OR",
["AND", "($IP = "127.1.2.3" )", "($AX < 15)"],
["AND", "(($IP = "127.1.2.4" )", ($AY != 0))"] ]

This problem is right down the pyparsing fairway! Pyparsing is a
module for defining recursive-descent parsers, and it has some built-
in help just for applications such as this.
Sometimes I've seen you proposing the usage of PyParsing on problems that,
in my opinion, were better solved using some other standard tools, but
this time you're absolutely right: this is perfectly suited for PyParsing!
:)

--
Gabriel Genellina

Apr 9 '07 #4
On Apr 9, 8:19 am, "Michael Yanowitz" <m.yanow...@kea rfott.comwrote:
Hello:

I have been searching for an easy solution, and hopefully one
has already been written, so I don't want to reinvent the wheel:
Pyparsing is indeed a fine package, but if Paul gets to plug his
module, then so do I! :)

I have a package called ZestyParser... a lot of it is inspired by
Pyparsing, actually, but I'm going in a different direction in many
areas. (One major goal is to be crazily dynamic and flexible on the
inside. And it hasn't failed me thus far; I've used it to easily parse
grammars that would make lex and yacc scream in horror.)

Here's how I'd do it...

from ZestyParser import *
from ZestyParser.Hel pers import *

varName = Token(r'\$(\w+) ', group=1)
varVal = QuoteHelper() | Int
sp = Skip(Token(r'\s *'))
comparison = sp.pad(varName + CompositeToken([RawToken(sym) for sym in
('=','<','>','> =','<=','!=')]) + varVal)
#Maybe I should "borrow" PyParsing's OneOf idea :)

expr = ExpressionHelpe r((
comparison,
(RawToken('(') + Only(_top_) + RawToken(')')),
oper('NOT', ops=UNARY),
oper('AND'),
oper('OR'),
))

Now you can scan for `expr` and get a return value like [[['IP', '=',
'127.1.2.3'], ['AX', '<', 15]], [['IP', '=', '127.1.2.4'], ['AY', '!
=', 0]]] (for the example you gave).

Note that this example uses several features that won't be available
until the next release, but it's coming soon. So Michael, though you'd
still be able to parse this with the current version, the code
wouldn't look as nice as this or the Pyparsing version. Maybe just add
it to your watchlist. :)

- Adam

Apr 10 '07 #5
En Tue, 10 Apr 2007 08:12:53 -0300, Michael Yanowitz
<m.********@kea rfott.comescrib ió:
I guess what I was looking for was something simpler than parsing.
I may actually use some of what you posted. But I am hoping that
if given a string such as:
'((($IP = "127.1.2.3" ) AND ($AX < 15)) OR (($IP = "127.1.2.4" ) AND ($AY
!=
0)))'
something like split(), where I can pass it something like [' AND ', '
OR
', ' XOR ']
will split the string by AND, OR, or XOR.
BUT split it up in such a way to preserve the parentheses order, so
that
it will
split on the outermost parenthesis.
So that the above string becomes:
['OR', '(($IP = "127.1.2.3" ) AND ($AX < 15))', '(($IP = "127.1.2.4" ) AND
($AY != 0))']
No need to do this recursively, I can repeat the process, however if I
wish on each
string in the list and get:
['OR', ['AND', '($IP = "127.1.2.3" )', '($AX < 15)'], ['AND', '($IP =
"127.1.2.4" )', '($AY != 0)']]

Can this be done without parsers?
This is exactly what parsers do. Sure, it can be done without using a
preexistent general parser, but you'll be writing your own specialized one
by hand.
Perhaps with some variation of re or
split.
Regular expressions cannot represent arbitrary expressions like yours
(simply because they're not regular).
If you know beforehand that all input has some fixed form, like "condition
AND condition OR condition AND condition", or at least a finite set of
fixed forms, it could be done with many re's. But I think it's much more
work than using PyParsing or similar tools.

If you have some bizarre constraints (parserphobia?) or for whatever
reason don't want to use such tools, the infix evaluator posted yesterday
by Gerard Flanagan could be an alternative (it only uses standard modules).
Has something like this already been written?
Yes, hundreds of times since programmable computers exist: they're known
as "lexers" and "parsers" :)

--
Gabriel Genellina

Apr 10 '07 #6

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

Similar topics

16
2435
by: Paul Prescod | last post by:
I skimmed the tutorial and something alarmed me. "Strings are a powerful data type in Prothon. Unlike many languages, they can be of unlimited size (constrained only by memory size) and can hold any arbitrary data, even binary data such as photos and movies.They are of course also good for their traditional role of storing and manipulating text." This view of strings is about a decade out of date with modern programmimg practice. From...
27
31423
by: The Bicycling Guitarist | last post by:
Hi. I found the following when trying to learn if there is such a thing as a non-breaking hyphen. Apparently Unicode has a ‑ but that is not well-supported, especially in older browsers. Somebody somewhere said: Alternately, you can use CSS to declare a class having: ..nowrap { white-space:nowrap } .... and then wrap the compound word in a <span class=nowrap></span> tag (or any other suitable inline tag). You can also try {...
150
6579
by: tony | last post by:
If you have any PHP scripts which will not work in the current releases due to breaks in backwards compatibility then take a look at http://www.tonymarston.net/php-mysql/bc-is-everything.html and see if you agree with my opinion or not. Tony Marston http://www.tonymarston.net
6
4701
by: Giff | last post by:
Hi I have this problem that I can't solve, I know it shouldn't be hard but I'm not a good coder and I'm going crazy tonight... I have a txt file that goes like this: string1 string2 string3 string4
6
5745
by: Christian Blackburn | last post by:
Hi Gang, When encoding HTML strings it'll convert things like " --> &rsquo and the like using Server.HTMLEncode(). However, is there a command to make sure strings don't contain valid SQL commands? Like I wouldn't want a string to contain "; Drop TableXYX;" or something along those lines. Thanks, Christian Blackburn
7
2266
by: temp34k45k | last post by:
I need to evaluate two strings for their order. The strings contain Letters (A thru Z upper case only) and Numbers (0-9) and the decimal point (.). I need an order like the list that follows: ( it's just an example of the order ) 0 1
1
1624
by: Jetboy555 | last post by:
Sample input: 2000 Georgia Tech 30 Virginia 20 1999 Virginia 20 Virginia tech My Problem is in taking the input in correctly. I take the year in correctly, but i'm having trouble with the names because some of them are two strings long. right now i have input << year << Winner1 << Winner2 < Score << Loser1 < Loser2 << Score
95
5417
by: hstagni | last post by:
Where can I find a library to created text-based windows applications? Im looking for a library that can make windows and buttons inside console.. Many old apps were make like this, i guess ____________________________________ | | | ------------------ | | | BUTTON | | | ...
2
1329
by: gitimaya | last post by:
hi, can anyone please help me in breaking up a string in array of strings. The delimeter is a character declared as '\001'. lets say i have a string as char d='\001' xxx'd'yyy'd'aaa i need that in an string array 1st element to be xxx and so on.
0
9589
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
9423
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
10212
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
10047
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
9995
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
9863
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
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3962
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

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.