Scala: Check if a String fully matches a Regex

Scala has more than one way to force a regular expression to match an entire string.

In all programming languages that support regular expressions, you can include special character classes in the regular expression, which match the beginning and end – ^ is the beginning of a line, and $ is the end.

For instance this will match a string that is nothing but “word” characters (letters / numbers). Note that the “\” has to be specified twice, because it is used to indicate special characters, like the end of line character (\n).

val regex = "^\\w+$".r

Scala adds to this a function called “anchored”, which forces the string to match the beginning and end of the line. Note that this is implemented completely separately from the character classes, so if either is set, Scala matches the entire string. Also note that while you can call “unanchored” to reset “anchored”, you can’t reset character classes.

Thus, the following does the same as the above example:

val regex = "\w+".r.anchored

Leave a Reply

Your email address will not be published. Required fields are marked *