1

I am trying to match two string which has '+' symbol in it.

val mystring = "test+string"
val tomatch = "test+string"

mystring.matches(tomatch)
This returns False.

tried to escape the + with \+ however it doesn't work.

sandyyyy
  • 75
  • 11

1 Answers1

3

Escaping + is correct, as \+ matches a literal +. There are more characters that need to be escaped in regex patterns, see What special characters must be escaped in regular expressions?

In Scala, you may use """....""" triple-quoted string literal to use just 1 backslash. See the Scala regex help:

Since escapes are not processed in multi-line string literals, using triple quotes avoids having to escape the backslash character, so that "\\d" can be written """\d""". The same result is achieved with certain interpolators, such as raw"\d".r or a custom interpolator r"\d" that also compiles the Regex.

So, use

val mystring = "test+string"
val tomatch = """test\+string"""
mystring.matches(tomatch)

See the Scala demo

Else, in a regular (non-"raw") string literal, you would need double backslashes:

val tomatch = "test\\+string"

If a whole string pattern should be treated as a literal string, use

import scala.util.matching.Regex

and then

val tomatch = Regex.quote("test+string")

The Regex.quote will escape all special chars that should be escaped correctly.

Another Scala demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563