From: Tom Cloyd Date: 2009-02-08T05:50:01+09:00 Subject: Re: cannot remove multiple space> nuts! David A. Black wrote: > Hi -- > > On Sat, 7 Feb 2009, Tom Cloyd wrote: > >> Tom Cloyd wrote: >>> I'm baffled by this strange outcome - I cannot reduce multiple >>> spaces from a text file. This isn't just a regex problem, somehow. >>> I'm failing to grasp something essential, but don't know what it is. >>> All help appreciated, as usual! >>> >>> Here is a demo of my problem, in which I try two different ways, and >>> both fail: >>> >>> === code === >>> # h2t.rb >>> >>> def main >>> # conversion table spec >>> conv = [ >>> [ '

', 'h1. ' ], [ '

', 'h2. ' ], [ '

', 'h3. ' ], >>> [ '

', 'h4. ' ], [ '

', 'h5. ' ], [ '
', 'h6. ' ], [ >>> /<\/h\d>/, '' ], >>> [ " +", ' ' ]] # <= this last array element should do the trick, >>> but doesn't >> Ouch. THIS - [ / +/, ' ' ], substituted for [ " +", ' ' ] above fixes >> it. I'm going blind, obviously. > > Just for fun, here's another way to write the method: > > def main > data = File.read("tom.txt") > data.gsub!(/<(h[1-6])>/, "\\1. ") > data.gsub!(/<\/h\d>/, "") > data.squeeze!(' ') > > open("tom.out", "w") {|f| f.write(data) } > > end > > I think that does the same thing. Tweak to taste :-) > > > David > That's beautifully economical, and reveals a far better grasp of regex than I was able to attain last night. However, I'm having trouble with this line: data.gsub!(/<(h[1-6])>/, "\\1. ") It certain works, but I don't grasp the "\\1. " part. I haven't yet found anything that might shed light on this magic. How does it retain the 'h' and whatever digit follows it? It looks somehow like "\\" == retain matched alpha, and the "1" does the same for matched digits, but I really haven't a clue. Can you elucidate just a bit? Thanks! Tom -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tom Cloyd, MS MA, LMHC - Private practice Psychotherapist Bellingham, Washington, U.S.A: (360) 920-1226 << tc@tomcloyd.com >> (email) << TomCloyd.com >> (website) << sleightmind.wordpress.com >> (mental health weblog) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~