I'm trying to parse a string using pyparsing. Using the code below
import pyparsing as pyp
aString = "C((H2)(C(H3))) C((H1)(Cl1)) C(((C(H3))3))"
aSub = '(('+ pyp.Word('()'+pyp.srange('[A-Za-z0-9]'))+'))'
substituent = aSub('sub')
for t,s,e in substituent.scanString(aString):
print t.sub
I get no output. However, in string aString = "C((H2)(C(H3))) C((H1)(Cl1)) C(((C(H3))3))"
there are multiple occurences of ((stuff))
- specifically ((H2)(C(H3)))
, C((H1)(Cl1))
and C(((C(H3))3))
.
My understanding of Word()
was that the input (in the case of a single input, as I have) represents all possible character combinations that will successfully return a match.
Running the code
import pyparsing as pyp
aString = "C((H2)(C(H3))) C((H1)(Cl1)) C(((C(H3))3))"
aSub = '(' + pyp.Word(pyp.srange('[A-Za-z0-9]'))+')'
substituent = aSub('sub')
for t,s,e in substituent.scanString(aString):
print t.sub
gives an output of
['(', 'H2', ')']
['(', 'H3', ')']
['(', 'H1', ')']
['(', 'Cl1', ')']
['(', 'H3', ')']
All I've changed is an additional external set of parentheses, as well as the option of parentheses inside of the string, which the desired strings have. I'm not sure why the first program gives me nothing, while the second string gives me (part of) what I want.
As suggested in the comments by Paul McGuire I found that using
nestedExpr
was the best choice for my situation. Using the following codeI got an output of
Which is exactly what I wanted.
The problem is the pyparsing works left to right (source). So having the right parenthesis erases what you are searching for on the right. For instance:
returns