正则表达式工具捕获数字并计算总和?

时间:2022-09-11 21:48:22

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).

我正在寻找一种工具(在线或OSx),它可以使用正则表达式捕获字符串中的数字,然后将这些数字相加并显示总和(理想情况下还可以执行其他一些数学运算)。

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

我知道例如RegExr可以列出所有匹配,但它不能真正对它们执行任何操作。

Not sure if this question qualifies on *, 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.

我可以很容易地创建自己的定制工具来做到这一点,但我相信它会让我们所有人(我和那些最终在这个线程中寻找相同工具的人)重新使用已经存在的东西而不是每个我们发明了自己的*。

1 个解决方案

#1


0  

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

这可以使用一小段Ruby代码完成。

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.

您可以使用在线解释器(如REPL.IT)或本地使用Ruby解释器来运行它。

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

每次执行的操作可以通过修改{| sum,x |来改变总和+ x}。

{ |product, x| product * x }

{| product,x |产品* x}

#1


0  

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

这可以使用一小段Ruby代码完成。

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.

您可以使用在线解释器(如REPL.IT)或本地使用Ruby解释器来运行它。

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

每次执行的操作可以通过修改{| sum,x |来改变总和+ x}。

{ |product, x| product * x }

{| product,x |产品* x}