如何改进正则表达式以消除不必要的方法链接? [英] How do I improve regex to eliminate unnecessary method chaining?
本文介绍了如何改进正则表达式以消除不必要的方法链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此功能方法采用一个数字,并返回相同的值,以逗号分隔,这与美国的常见惯例相同.
This functional method takes a number and returns the same value separated with commas, as is the common convention in the US.
我可以使它与regex一起使用的唯一方法是在表达式前后反转字符串.是否有一个正则表达式可以帮助我消除两次调用String#reverse以实现方法功能的需要?
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
推荐答案
"1234556".gsub(/\d(?=\d{3}+\b)/,'\\0,')
# => "1,234,556"
这不能处理长分数,但这也不是OP的正则表达式的问题.
This doesn't handle long fractional values, but this wasn't a concern for the OP's regex either.
这篇关于如何改进正则表达式以消除不必要的方法链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文