Case insensitive Scala parser-combinator
Asked Answered
U

1

5

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.

Unify answered 21/5, 2011 at 8:2 Comment(0)
C
15

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
Catalectic answered 21/5, 2011 at 13:12 Comment(1)
Thank you! Works very nicely.Unify

© 2022 - 2024 — McMap. All rights reserved.