0

I'm looking for a tool (online or for OSx) that can capture numbers in a string using regex, and then sum up those numbers and display the sum (and ideally perform some other mathematical operations as well).

I know that for example RegExr can list all matches, but it can't really perform any operations on them.

Not sure if this question qualifies on StackOverflow, but I'm sure many developers out there have had the need to quickly and easily sum up some values in debug outputs (which is exactly what I need to do), so I'm throwing it out there anyway.

I could easily create my own tailor made tool to do it, but I'm sure it would benefit all of us (me and those who end up in this thread looking for the same tool) to reuse something that already exists instead of each of us inventing our own wheel.

Magnus
  • 17,157
  • 19
  • 104
  • 189
  • Sounds a bit like [this golf challenge](http://codegolf.stackexchange.com/q/47566), might be you find something useful there? Plus there have been similar question, e.g. [this one](http://stackoverflow.com/q/12941362/3890673), with some pretty extensive answers as well – crusy Feb 23 '17 at 07:06

1 Answers1

0

This can be done using a short piece of Ruby code.

source = "zaw34r5vgfyt78uibv879gu"

regex_numbers = /[0-9]+/
matches = source.scan(regex_numbers).collect { |str| str.to_f }
result = matches.inject { |sum, x| sum + x }

puts result

You can run it using an online interpreter, such as REPL.IT, or locally using a Ruby interpreter.

The operation performed each time can be changed by modifying { |sum, x| sum + x }.

{ |product, x| product * x }

Sekalf Nroc
  • 457
  • 3
  • 7