如何使用 ruby regexp 用类似“回调函数"的操作替换字符串 [英] How to use ruby regexp to substitute string with a "callback function"-like manipulation
本文介绍了如何使用 ruby regexp 用类似“回调函数"的操作替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有示例行,我想用 =
s 替换前导 #
s.(前两行)但是在string.gsub!(/^#+w/, "")
中,我无法得到我想要替换的#
的数量.
I have the samples lines, and I want to substitute the leading #
s with =
s. (The first two lines)
But instring.gsub!(/^#+w/, "")
, I can not get the number of #
which I want to substitute.
在 javascript 中,我可以使用带有 replace
方法的回调函数,但是我该如何存档这个 Ruby?
In javascript, I could use a callback function with the replace
method, but how could I archive this Ruby?
##Command-line Tool
###Installment
This is a '#'.
预期结果:
==Command-line Tool
===Installment
This is a '#'.
推荐答案
可能是 gsub 方法的回调块函数.我不确定你的想法,但可能是这样的
a callback block function to the gsub method, probably. I am not sure what you had in mind but could be something like
s.gsub(/^(#+)w+/) {|m| m.gsub("#", "=") }
这篇关于如何使用 ruby regexp 用类似“回调函数"的操作替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文