I’m sorry but my little brain is stuck w my first ruby program. The
program’s objective is to move the “-” sign of negative numbers to the front
;eg, fr 999.99- to -999.99
so I run:
C:\family\ruby>ruby negatives.rb negatives.txt
and the output is:
99.99- 9999- 99-99 99-99- 99999.99- 9.99-
My program (regex actually) works for figures even of the form 9999-999 or
99-99-. I do NOT want this since these numbers may be dates, telno, etc…
So how do I restrict my regex so that it will only process numbers of the
form 999- or 999.99- but not 999-999 or 999-99-
the file contents of negatives.rb and negatives.txt follow below.
#------------------- #negatives.rb
File.open(ARGV[0]) do |f|
f.each do |line|
puts line
puts (line.gsub ( /(\b)((\d+)|(\d+.\d+))(-)/,
‘>>\5\1\2<<’))
puts
end
end
It really depend on what you want : for a regexp the most difficult task
is the specification. When you have a *complete* specification, then you
can try to write it. For example I've added some cases
pigeon% cat b.rb
#!/usr/bin/ruby
DATA.each do |line|
puts line
puts line.gsub(/(^|[^-.\d])(\d+(?:\.\d+)?)-(?=[^-.\d]|$)/,'>>\1-\2<<')
puts
end
__END__
99.99- 9999- 9.- .99- -99.99- 9.9-. 99-99 99-99- 99999.99- 9.99-
pigeon%
I don’t know why I bother trying to hammer out answers to questions
like this when it’s still daylight in Paris… but anyway, I just
wanted to make one observation, for possible future reference.
Namely: there’s no point capturing a \b match and backreferencing it,
because it’s just a zero-width assertion. It doesn’t actually match
or consume a character in the string; it’s just a constraint on the
upcoming attempted match.
David
···
On Sat, 27 Jul 2002, [iso-8859-1] “Peña, Botp” wrote: