开发者

Scala regex replace with anonymous function

In Ruby I can replace characters in a string in the following way:

a = "one1two2three"
a.gsub(/\d+/) {|e| e.to_i +开发者_如何学C 1}
=> "one2two3three"

The result of evaluating the block from the second line, will replace what was matched in the pattern. Can we do something equivalent in Scala? Replace something in a regex with the results of a function/anonymous function?


Yes, Regex#replaceAllIn has an overloaded version that takes a function Match => String. The equivalent Scala version of your code would be:

"""\d+""".r.replaceAllIn("one1two2three", m => (m.group(0).toInt + 1).toString)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜