From: 7stud -- Date: 2007-11-23T19:50:23+09:00 Subject: Re: New at regexp and Ruby need help on parsing a string. 7stud -- wrote: > > Try this: > > str = 'and stuff and nice things not bad girls not greasy boys > and girlsandboys' > > smoking_table = {'and'=>[], 'not'=>[]} > > pieces = str.split(/(and |not )/) > len = pieces.length > > index = 0 > while index < len > > case pieces[index] > when 'and ' > smoking_table['and'] << pieces[index+1].strip > index +=2 > when 'not ' > smoking_table['not'] << pieces[index+1].strip > index += 2 > else > index += 1 > end > > end > > p smoking_table Normally when you split() a string, you do something like this: str = 'aXbXc' pieces = str.split('X') p pieces -->["a", "b", "c"] Notice that the pattern you use to split the string is not part of the results-it's chopped out of the string and the pieces are what's left over. However, there is a little known feature where if your split pattern has a group in it, which is formed by putting parenthesis around part of the patten, then the group will be returned in the results. I used parentheses around the whole split pattern to get a result array like this: ["", "and ", "stuff ", "and ", "nice things ", "not ", "bad girls ", "not ", "greasy boys\n", "and ", "girlsandboys"] By including the split pattern in the results, you can see that each piece of the string is preceded by either 'and ' or 'not '. The 'and ' or 'not ' then serves as an identifier for each piece of the string. -- Posted via http://www.ruby-forum.com/.