From: Park Heesob Date: 2002-07-04T12:54:37+09:00 Subject: Re: the pains of parsing "Tom Sawyer" wrote in message news:1025743968.2467.123.camel@silver... > i find myself spending alot of time writing routines to parse complex > strings. here's a mock example string of my current problem: > > a[c]{d}"e"f {{g}} [[h]]*i**j*"k" > > and i want to parse this into an array like so: > > ['a','','[c]','{d}','"e"','f','{{g}}','[[h]]','*i*','*j*','"k"'] > > for clearity here's another example: > > "a"{{b}}c{d} -> ['"a"','{{b}}','c','{d}',''] > > i have found such strings difficult to parse for a number of reasons. > first, the text in double-quotations could contain bracket symbols but > must be treated as plain text. second, [ and { brackets can be nested as > in g and h of the first example. and finally, because whitespace can > optionally occur between the parts. > > i wish ruby had some sort of parsing tool to make this childs play. > > can any of you geniuses out there offer an elegent solution? my current > code dosen't work 100% and is like 90+ lines long. ugghh! > > ~transami > Hi? How about this? -------------------------------------------------- str = 'a[c]{d}"e"f {{g}} [[h]]*i**j*"k"' s = ['<','[','{','"','*'] e = ['>',']','}','"','*'] arr = [] str.gsub!(' ','') i = 0 while i< str.length if not s.include?(str[i,1]) for j in i ... str.length if s.include?(str[j,1]) arr << str[i..j-1] i = j break end end end for j in 0 ... s.length if str[i,1] == s[j] if s[j]=='"' || s[j]=='*' k = str.index(e[j],i+1) else k = i k += 1 while str[k,1]==s[j] for k in str.index(e[j],k) ... str.length if str[k,1]!=e[j] k -= 1 break end end end arr << str[i..k] i = k+1 break end end end p arr --------------------------------------------- Park Heesob.