Korhan Ozturk
Korhan Ozturk

Reputation: 11308

Grab every character in String until a specified word Scala Regex

I'm new to Scala and trying to parse a very simple String and get every character until encountering "--batch" with the following String parser:

def getEntireMetaData : Parser[EntireMetaData] = """(?s).+?(?=--batch)""".r ^^ { EntireMetaData}

And I call it as the following:

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) 
}

which gives me the error

[7.1] failure: string matching regex `\z' expected but `-' found

--batch_36522ad7-fc75-4b56-8c71-56071383e77b

^

The following is what I want my parser to match:

"POST /service/$batch HTTP/1.1 \nHost: host \n +
"Content-Type: multipart/mixed;boundary=batch_36522ad7-fc75-4b56-8c71-56071383e77b\n \n"

Please help me sort this out.

Thanks in advance

Upvotes: 1

Views: 1085

Answers (1)

Daniel Langdon
Daniel Langdon

Reputation: 5999

Ok, you have a few different issues:

  1. You are not actually catching your match
  2. You are missing a " after \nHost: host \n

Overall, the following expression does what you want: (?s)(.+?)(?=--batch)

On the other hand, you hardly need a regex for this:

batchRequest.substring(0, batchRequest.indexOf("--batch"))

gets you:

POST /service/$batch HTTP/1.1 Host: host Content-Type: multipart/mixed;boundary=batch_36522ad7-fc75-4b56-8c71-56071383e77b

You can also check if indexOf returns -1 before of course.

Upvotes: 1

Related Questions