sergeda
sergeda

Reputation: 2201

Regex Negated character class problem, Scala

With this code I'm trying to get only "key" and "value" from the string. But function return None. If I change [^"]+ to .+ then it would return result but value would contain none-needed part as well. How to fix this issue?

def parseLine(line: String): Option[(String, String)] = {
    val exportRegex = """\s*export\s+(\S+)\s*="([^"]+)"""".r
    line match {
      case exportRegex(key, value) =>Some(key, value)
      case _ => None
    }
  }

parseLine("""export key="value" #"none-needed"""")

Upvotes: 1

Views: 30

Answers (1)

jwvh
jwvh

Reputation: 51271

The problem is that ...([^"]+)""" means that the input should end with the capture group, even before any closing quote mark.

To fix it you can A) add .* at the end (i.e. ...([^"]+).*""") or B) make the regex .unanchored, in which case you can probably drop the \s* at the beginning.

Upvotes: 1

Related Questions