正则表达式"标签:价值,标签:价值,......"

时间:2015-11-06 16:53:45

标签: regex scala

我有一个字符串,看起来像逗号分隔的"标签:值"项目

package testParsers

import org.scalatest.{Matchers, FlatSpec}

class testReturnStrParser extends FlatSpec with Matchers{
  import parsers.ReturnStringParser

  "return string parser" should "find the height in ret string" in {
    val teststr = "blahblah:123, height:80.3"
    val s = ReturnStringParser.findVal("height", teststr)
    s should have length 1
    s.head shouldEqual ("80.3")
  }

  it should "work if it is in the middle" in {
    val teststr = "blahblah:123, height:80.3,weight:100.0"
    val s = ReturnStringParser.findVal("height", teststr)
    s should have length 1
    s.head shouldEqual ("80.3")
  }

}

当标签height位于中间时,我正在努力使课程正常工作:

package parsers

object ReturnStringParser {
  def findVal(fieldName: String, s: String) = {
    val rx = s"(?<=$fieldName:)"+"(.*)*[^,\\s]*"
    (rx.r)
      .findAllIn(s)
      .toList
  }
}

1 个答案:

答案 0 :(得分:0)

这有效:

val rx = s"(?<=$fieldName:)"+"([^,]*)"

https://regex101.com/r/aC4vA3/1