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

Interested in Scala? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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