在 Scala 中提取正则表达式后的元素

Extract the elements after the regex in Scala

我在数据框中有一列,其数据如下。现在我只需要 test1

之后的元素

即它应该 return abc,efg,ghg ,并且每行的长度也不同。

 test1:abc,test2:ghr,test2:jkl,test1:efg,test3:erp dfg (jfg),test1:ghg

我正在尝试在 test1 之后的部分上写一个方法 return,我试过如下。 但它不会完全按照我的意图工作 achieve.Please 让我知道是否有办法实现它

def findStr(str:String):Array[String]= {
  if (str.contains ("test1:") ) {
  val res = test.split ("test1:")
 for (i <- res.length - 1) {
  val res1 = res (i)
 if (res1.contains (",") ) {
   val res2 = res1.split (",")(0)
    }
  else null
  }
 else null
 }

一种方法:

val input = " test1:abc,test2:ghr,test2:jkl,test1:efg,test3:erp dfg (jfg),test1:ghg"

input
  .split(",")
  // Array(" test1:abc", test2:ghr, test2:jkl, test1:efg, test3:erp dfg (jfg), test1:ghg)
  .map(_.split(":"))
  // Array(Array(" test1", abc), Array(test2, ghr), Array(test2, jkl), Array(test1, efg), Array(test3, erp dfg (jfg)), Array(test1, ghg))
  .filter{ case Array(k, v) => k.trim == "test1" }
  // Array(Array(" test1", abc), Array(test1, efg), Array(test1, ghg))
  .map{ case Array(k, v) => v }
  // Array(abc, efg, ghg)
  .mkString(",")
  // "abc,efg,ghg"

此解决方案假定输入字符串遵循以下格式:

key1:valueA,key2:valueB:key1:valueC,...

因为您有一个由 "," 分隔的键值结构,所以您可以根据“,”进行拆分,而不是在 test1 上拆分。

这为您提供了一个 key/value 字符串序列,这为您提供了一种简单的方法来单独处理 "test1".

的键

我认为你选择了一个递归函数,你在 test1 上拆分,它直接在 test1 之后给你值,你可以用拆分的左边部分再次调用你的函数,以便找到下一个 "test1",依此类推。但我认为在这种情况下有点矫枉过正。

作为旁注,我建议不要在 Scala 中使用 null 而是使用 Option monad.