我是Scala的新手并尝试解析一个非常简单的字符串并获取每个字符,直到遇到" - 批处理"使用以下字符串解析器:
def getEntireMetaData : Parser[EntireMetaData] = """(?s).+?(?=--batch)""".r ^^ { EntireMetaData}
我将其称为以下内容:
val batchRequest: String = "POST /service/$batch HTTP/1.1 \nHost: host \n +
"Content-Type: multipart/mixed;boundary=batch_36522ad7-fc75-4b56-8c71-56071383e77b\n \n" +
"--batch_36522ad7-fc75-4b56-8c71-56071383e77b "
implicit val p = parser.getEntireMetaData
parser.parseAll(p, batchRequest) match {
case result: parser.Success[_] => println(result.get)
case result: parser.NoSuccess => fail(result.toString)
}
给了我错误
[7.1] failure: string matching regex `\z' expected but `-' found
--batch_36522ad7-fc75-4b56-8c71-56071383e77b
^
以下是我希望我的解析器匹配的内容:
"POST /service/$batch HTTP/1.1 \nHost: host \n +
"Content-Type: multipart/mixed;boundary=batch_36522ad7-fc75-4b56-8c71-56071383e77b\n \n"
请帮我解决这个问题。
提前致谢
答案 0 :(得分:1)
好的,你有几个不同的问题:
\nHost: host \n
之后总体而言,以下表达式可以满足您的需求:(?s)(.+?)(?=--batch)
另一方面,你几乎不需要正则表达式:
batchRequest.substring(0, batchRequest.indexOf("--batch"))
得到你:
POST /service/$batch HTTP/1.1
Host: host
Content-Type: multipart/mixed;boundary=batch_36522ad7-fc75-4b56-8c71-56071383e77b
您还可以检查indexOf
当前是否返回-1。