简体   繁体   中英

Regex matching: long String in Scala

I have a really long in-memory string stored in a val response: String that looks something like

HTTP/1.1 200 OK
Server: Apache
Other: headers

<response>
<xml>
---much much more XML---
</xml>
</response>
0

I want to extract the

<response>
...
</response>

part of the string. So far, I have this:

"<response>.*?</response>".r findFirstIn response

...but for some reason Scala returns None. I did figure out a way to do this with indices and the slice function, but there has to be a neat way with regex. Anyone know how?

First of all, it is probably a much better idea to use an XML parser when working with XML responses. It might look like an overkill at first, but as the project grows it is very likely that you'll end up with having to parse more complicated XML documents, which will be much harder with regex than with a full-fledged XML parser.

Anyway, this regex works:

"(?s)<response>.*?</response>".r findFirstIn response

(?s) sets the DOTALL flag .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM