大家好,我对scala有点陌生,我有个问题:
在以下字符串上:
The ID 5d27e5d082c272591e25b8d5 is the only valid Field,
The ID 5d27e5d06a77457139395318 is the only valid Field,
The ID 5d27e5d0431e726aeb5ab84f is the only valid Field,
The ID 5d27e5d282c27256cc24b6a2 is the only valid Field,
The ID 5d27e5d282c27256cc24b6a2 is the only valid Field,
The ID 5d27e5d282c2727ad524c567 is the only valid Field,
The ID 5d27e5d2431e724af25a1bd6 is the only valid Field,
The ID 5d27e5d36a774507723a7ea2 is the only valid Field,
The ID 5d27e5d36a774507723a7ea2 is the only valid Field,
The ID 5d27e5d482c2727ad524c576 is the only valid Field,
The ID 5d27e5d482c272591e25b8ee is the only valid Field,
The ID 5d27e5d482c2727ad524c576 is the only valid Field,
The ID 5d27e5d482c2727ad524c576 is the only valid Field
我有一组通过验证过程的id。
如何创建一个新字符串,将id分组如下:
The id 5d27e5d282c27256cc24b6a2 has 4 errors
The id 5d27e5d482c2727ad524c576 has 2 errors
....
试过了,但我觉得有更好的方法
val replaced = input.replaceAll("The ID","").replaceAll("is the only valid Field","").trim.split(",").map(_.trim).groupBy(l => l).map(t => (t._1, t._2.length))
var newMessage = ""
replaced.foreach(s => {
newMessage += s"The ID ${s._1} the only valid field on ${s._2.toString} rows, "
})
谢谢!
最佳答案
这与其他响应有点相似,但有一个安全的模式匹配:
val LineRegEx = "The ID (.+) is the only valid Field,?".r
val output =
input
.split('\n')
.collect {
case LineRegEx(id) => id
}
.groupBy(identity)
.map { case (id, rows) =>
s"The ID $id the only valid field on ${rows.length} rows"
}
.mkString("\n")
关于string - 如何在Scala字符串中找到ID的出现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57115622/