Scala 正则表达式替换为匿名函数 [英] Scala regex replace with anonymous function

查看:53
本文介绍了Scala 正则表达式替换为匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,我可以通过以下方式替换字符串中的字符:

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

a = "one1two2three"
a.gsub(/\d+/) {|e| e.to_i + 1}
=> "one2two3three"

从第二行计算块的结果将替换模式中匹配的内容.我们可以在 Scala 中做一些等价的事情吗?用函数/匿名函数的结果替换正则表达式中的某些内容?

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?

推荐答案

是的,Regex#replaceAllIn 有一个重载版本,它接受一个函数 Match =>字符串.您的代码的等效 Scala 版本将是:

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)

这篇关于Scala 正则表达式替换为匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆