gpt4 book ai didi

regex - 如何正确使用scala.util.matching.Regex?

转载 作者:行者123 更新时间:2023-12-01 21:36:39 24 4
gpt4 key购买 nike

这可能看起来很明显,但我无法解释 No match available 错误 。下面是我正在使用的简单匹配函数的定义。

函数内的相同指令运行没有问题,但是调用该函数会引发错误。你能帮我找出错误吗?

import scala.util.matching.Regex

def regexParsing(inputRecord:String, inputRegex:String, listOfFields:Seq[String], fieldsToRemove:Seq[String]): scala.collection.Map[String,Any] = {
val logPattern = new Regex(inputRegex, listOfFields:_*)
val result = logPattern.findAllIn(inputRecord)
val resultMap = result.groupNames.map(a => Map(a.toString -> result.group(a))).reduce(_++_)
return resultMap
}

val inputRecord = """s2222f"""
val inputRegex = """(.*)"""
val listOfFields = Seq("field")
val fieldsToRemove = Seq("field1", "field2")

// working
val logPattern = new Regex(inputRegex, listOfFields:_*)
val result = logPattern.findAllIn(inputRecord)
val resultMap = result.groupNames.map(a => Map(a.toString -> result.group(a))).reduce(_++_)

// not working
regexParsing(inputRecord, inputRegex, listOfFields, fieldsToRemove)

最佳答案

尝试 2.12?关于推进迭代器的限制是 API 中的一个问题,最终得到了解决。

$ scala
Welcome to Scala 2.12.0-RC1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions for evaluation. Or try :help.

scala> :pa
// Entering paste mode (ctrl-D to finish)

import scala.util.matching.Regex

def regexParsing(inputRecord:String, inputRegex:String, listOfFields:Seq[String], fieldsToRemove:Seq[String]): scala.collection.Map[String,Any] = {
val logPattern = new Regex(inputRegex, listOfFields:_*)
val result = logPattern.findAllIn(inputRecord)
val resultMap = result.groupNames.map(a => Map(a.toString -> result.group(a))).reduce(_++_)
return resultMap
}

val inputRecord = """s2222f"""
val inputRegex = """(.*)"""
val listOfFields = Seq("field")
val fieldsToRemove = Seq("field1", "field2")

// working
val logPattern = new Regex(inputRegex, listOfFields:_*)
val result = logPattern.findAllIn(inputRecord)
val resultMap = result.groupNames.map(a => Map(a.toString -> result.group(a))).reduce(_++_)

// Exiting paste mode, now interpreting.

import scala.util.matching.Regex
regexParsing: (inputRecord: String, inputRegex: String, listOfFields: Seq[String], fieldsToRemove: Seq[String])scala.collection.Map[String,Any]
inputRecord: String = s2222f
inputRegex: String = (.*)
listOfFields: Seq[String] = List(field)
fieldsToRemove: Seq[String] = List(field1, field2)
logPattern: scala.util.matching.Regex = (.*)
result: scala.util.matching.Regex.MatchIterator = non-empty iterator
resultMap: scala.collection.immutable.Map[String,String] = Map(field -> s2222f)

scala> regexParsing(inputRecord, inputRegex, listOfFields, fieldsToRemove)
res0: scala.collection.Map[String,Any] = Map(field -> s2222f)

scala> :quit

关于regex - 如何正确使用scala.util.matching.Regex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40091762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com