How do I improve regex to eliminate unnecessary method chaining?

微笑、不失礼 提交于 2019-12-25 03:06:42

问题


This functional method takes a number and returns the same value separated with commas, as is the common convention in the US.

The only way I could get it to work with regex was to reverse the string before and after the expression. Is there a regex that can help me eliminate the need to call String#reverse twice for method functionality?

def separate_comma(number)
  raise "You must enter a number." if number.is_a?(Numeric) == false
  number.to_s.reverse.gsub(/(\d{3})(?=\d{1,3})/, "\\1,").reverse
end

回答1:


"1234556".gsub(/\d(?=\d{3}+\b)/,'\\0,')
# => "1,234,556"

This doesn't handle long fractional values, but this wasn't a concern for the OP's regex either.




回答2:


Other libraries have already solved this problem - ActiveSupport for one.

require "active_support/number_helper"
ActiveSupport::NumberHelper.number_to_delimited(1234567890)
#=> "1,234,567,890"

You can even change the delimiter if you wish:

ActiveSupport::NumberHelper.number_to_delimited(1234567890, delimiter: "|")
#=> "1|234|567|890"



回答3:


The established way to do it is:

string.gsub(/(?<=\d)(?=(?:\d{3})+\z)/, ",")

If you want to do it with floats:

string.gsub(/(?<=\d)(?=(?:\d{3})+[.\z])/, ",")


来源:https://stackoverflow.com/questions/21892046/how-do-i-improve-regex-to-eliminate-unnecessary-method-chaining

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!