----- Original Message ----- 
From: "Stephen White" <spwhite / chariot.net.au>
To: "ruby-talk ML" <ruby-talk / ruby-lang.org>
Sent: Tuesday, June 05, 2001 12:20 PM
Subject: [ruby-talk:16241] Re: String#scan strange behavior


> On Wed, 6 Jun 2001, Wayne Blair wrote:
> 
> > >   irb(main):006:0> "one two three".scan(/\w+/)
> > >   ["one", "two", "three"]
> > >
> > > Works for me anyway. :)
> > 
> > Right, but if you have to use a subexpression, you are out of luck, for
> > example when you want to match between 2 quotes but allow for escaped
> > quotes:
> > 
> > /"(\\"|[^"])*"/
> 
> Guy's solution is much better, but you can do it with sub-expressions
> if you flatten and compact the result. Eg:
> 
>   "one two three".scan(/"(\\"|[^"])*"/).flatten.compact
> 
> -- 
>   spwhite / chariot.net.au

Guy's solution is right, but flatten.compact does not work the same:

a = "one \"\\\"quoted\\\"\" three"
def parseCommandLine(aString)
  aString.scan(/\w+|"(\\"|[^"])*"/).flatten.compact
end
#subexpression result just not nested in array
parseCommandLine(a) #=> ["\\\""] 

WHEREAS

a = "one \"\\\"quoted\\\"\" three"
def parseCommandLine(aString)
  aString.scan(/\w+|"(?:\\"|[^"])*"/)
end
# desired result
parseCommandLine(a) #=> ["one", "\"\\\"quoted\\\"\"", "three"] 

Thanks again for the collaboration,

Wayne