我需要将给定字符串中的分数替换为十进制。所以:
1/4 xx -> 0.25 xx
1/3 xx -> 0.33 xx
上面的例子我涵盖了:
private fun String.replaceFractions() = "(?:[1-9]*)/[1-9]*".toRegex().find(this)
?.let {
val fraction = it.groups[0]!!.value
val fractionParts = fraction.split("/")
.map { part -> part.toDouble() }
this.replace(fraction, (fractionParts[0] / fractionParts[1]).toString())
}
?: this
但是当它们也有整个部分时,我找不到正确替换字符串的方法:
1 1/4 xx -> 1.25 xx
3 3/5 xx -> 3.6 xx
你可以实现你想要一个单纯的是什么replace
样
val s = "Some text: 1/4 and 3 3/5"
val result = s.replace("""(?:(\d+(?:\.\d+)?)\s+)?(\d+)/(\d+)""".toRegex()) {
((if (it.groupValues[1].isNullOrEmpty()) 0.0 else it.groupValues[1].toDouble()) + (it.groupValues[2].toDouble() / it.groupValues[3].toDouble())).toString()
}
println(result) // => Some text: 0.25 and 3.6
正则表达式详情
(?:(\d+(?:\.\d+)?)\s+)?
- 一个可选的非捕获组匹配 1 或 0 次出现:
(\d+(?:\.\d+)?)
- 第 1 组:1+ 位数字,然后是 1 或 0(可选).
和 1+ 位数字的序列\s+
- 1+ 个空格(\d+)
- 第 2 组:1+ 位数字/
- 一个/
字符(\d+)
- 第 3 组:1+ 位数字如果第 1 组匹配,则将其值强制转换为双精度值,否则0
取值,并将该值与第 2 组和第 3 组划分的结果相加。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句