Scala/Java: How to write a pattern that matches a minimum to maximum number of specified characters
By Alvin Alexander. Last updated: April 24 2018
If you’re using Java or Scala and need to write a pattern that matches a range of characters, where those characters occur between a minimum and maximum number of times in the pattern, the following example shows a solution I’m currently using.
The idea is that the pattern "[a-zA-Z0-9]{1,4}"
means, “Match a string that has only the characters a-z, A-Z, and 0-9, where those characters occur a minimum of one time and a maximum of four times.” The following tests in the Scala REPL shows how this works: