Andres
Andres

Reputation: 1454

Case insensitive Scala parser-combinator

I'm trying to create a language, and there are some parts of it that I want to be case insensitive. I'm sure this is something easy, but I haven't been able to find it.

Edit: Re-reading makes me ashamed of this question. Here is a failing test that explains what I mean.

Upvotes: 5

Views: 1458

Answers (1)

David Winslow
David Winslow

Reputation: 8590

Use a regular expression instead of a literal.

lazy val caseSensitiveKeyword: Parser[String] = "casesensitive"
lazy val caseInsensitiveKeyWord: Parser[String] = """(?i)\Qcaseinsensitive\E""".r

(See the docs for java.util.Pattern for info on the regex syntax used.)

If you're doing this frequently you could pimp String to simplify the syntax:

class MyRichString(str: String) {
  def ignoreCase: Parser[String] = ("""(?i)\Q""" + str + """\E""").r
}

implicit def pimpString(str: String): MyRichString = new MyRichString(str)

lazy val caseInsensitiveKeyword = "caseinsensitive".ignoreCase

Upvotes: 15

Related Questions