monica
monica

Reputation: 1065

How can I match square bracket in Regex Scala?

I am trying to match [and ]. but the when we also use the two for regular expression, how can I write some pattern to match the two brackets? Using \[ does not work as it gives out compiler error for the following line:

 regex(new Regex("([^.#; \\t\\r\n(){}\[\]',`\"][^; \\t\\r\\n(){}\[\]',`\"]*|[.][^; \\t\\r\\n(){}\[\]',`\"]+)"))

Upvotes: 3

Views: 4792

Answers (2)

Andreas Neumann
Andreas Neumann

Reputation: 10894

I'd go with

"""\[[^\]]+\]""".r

for the Regex.

"""\[[^\]]+\]""".r findAllIn """[a], [b], [123 Hello]""" toList
res2: List[String] = List([a], [b], [123 Hello])

The Regex would work fine as long as you won't need to parse nested expressions as in

"""\[[^\]]+\]""".r findAllIn """[[a], [b]]""" toList
res4: List[String] = List([[a], [b])

Upvotes: 5

Malte Schwerhoff
Malte Schwerhoff

Reputation: 12852

val Bracketed = """\[.*?\]""".r

def check(s: String) =
  (Bracketed findAllIn s).toSeq

check("Wrong (curved) thingies") // Nil
check("") // Nil
check("[Hi]") // [Hi]
check("[Hi][There]") // [Hi], [There]
check("[Hi]gap[There]gop") // [Hi], [There]

Upvotes: 2

Related Questions