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.
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 asraw"\d".ror a custom interpolatorr"\d"that also compiles theRegex.
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.
