From: William James Date: 2007-08-30T03:00:14+09:00 Subject: Re: gsub help On Aug 28, 11:46 pm, Pe�a, Botp wrote: > From: hurcan solter [mailto:hsol...@gmail.com] > # line.gsub!(/\s*([=]+)\s*/ ,' \1 ') > # > # But it applies every = on the line ofc, but I want to exclude > # expressions between quotation marks ("sth=sth") or regexp (/sth=sth/). > > after reviewing WJames post (thanks james), i think you are not far to the solution. You just need to include the exceptions first, then gsub further to that. gsub accepts a block, so flexibility is unlimited, eg, > > > str > > => "/x==9/ { print \"x==9 and AWK is everywhere!\"; x=9 }" > > let's create our main regex sub and test if we can get back to the original str, > > > p str.gsub(/\S*\s*([=]+)\s*\S*/){|s| s } > > "/x==9/ { print \"x==9 and AWK is everywhere!\"; x=9 }" > => nil > > ok. now let's view our captures. let's put some markers/tags. > > > p str.gsub(/\S*\s*([=]+)\s*\S*/){|s| "<<"+s+">>" } > > "<> { print <<\"x==9>> and AWK is everywhere!\"; <> }" > => nil > > ah, i think we're capturing right for this case of str > > now let's test the inner substitution. note the gsub inside the block. the expression gets simpler since we've already filtered thru the first/main regexp. > > > p str.gsub(/\S*\s*([=]+)\s*\S*/){|s| s.gsub(/(=+)/,' \1 ') } > > "/x == 9/ { print \"x == 9 and AWK is everywhere!\"; x = 9 }" > => nil > > ok. > now, let us combine that one w the first one (the noop), using an inline if (i'm assumming you want a one-liner) filtering thru the exception you want, ie, no ["\/] > > > p str.gsub(/\S*\s*([=]+)\s*\S*/){|s| s=~/["\/]/ ? s : s.gsub(/(=+)/,' \1 ') } > > "/x==9/ { print \"x==9 and AWK is everywhere!\"; x = 9 }" > => nil >> irb --prompt xmp str='/x==9/ {print "so x=9 and AWK is everywhere!"; x=9 }' ==>"/x==9/ {print \"so x=9 and AWK is everywhere!\"; x=9 }" str.gsub(/\S*\s*([=]+)\s*\S*/){|s| s=~/["\/]/ ? s : s.gsub(/(=+)/,' \1 ') } ==>"/x==9/ {print \"so x = 9 and AWK is everywhere!\"; x = 9 }"