From: William James Date: 2008-02-12T06:44:56+09:00 Subject: Re: Return number of matches On Feb 11, 8:41 am, Jano Svitok wrote: > On Feb 11, 2008 3:24 PM, Christopher Causer wrote: > > > This seems like an easy question but I cannot find any documentation on > > it anywhere on the web. > > > I want to write a script that will count the number of dollars in a > > string, excluding escaped dollars (ie. "\$".) My first hack was to use > > split and count the number of elements in the array, but I came unstuck > > trying to exclude \$. Surely there's a nice simple elegant solution? > > Easy solution: count $ and subtract \$ ;-) > > string.scan(/\$/).size - string.scan(/\\\$/).size > > It's possible to do it in one regex, but it won't be nice and elegant > and I don't have the time now to try it... That fails when the backslash preceding a $ is itself escaped. >> irb --prompt xmp string = "$\\\\$" ==>"$\\\\$" string.scan(/\$/).size - string.scan(/\\\$/).size ==>1 Try this: p DATA.read.scan(/(\\.|[$])/).flatten.grep(/^.$/).size __END__ $\\$\$$