Scala/Java: How to write a pattern that matches a minimum to maximum number of specified characters

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:

scala> val pattern = "[a-zA-Z0-9]{1,4}"
pattern: String = [a-zA-Z0-9]{1,4}

scala> "".matches(pattern)
res0: Boolean = false

scala> " ".matches(pattern)
res1: Boolean = false

scala> "f".matches(pattern)
res2: Boolean = true

scala> "foob".matches(pattern)
res3: Boolean = true

scala> "foobar".matches(pattern)
res4: Boolean = false

scala> "FOOB".matches(pattern)
res5: Boolean = true

scala> "1234".matches(pattern)
res6: Boolean = true

scala> "1-234".matches(pattern)
res7: Boolean = false

While those examples are shown in Scala, they easily translate to Java if you need to use the same approach in Java code. If you need to do a pattern match on a string to look for a range of characters that occur somewhere between a minimum and maximum number of times, I hope this code is helpful. (And for more information, see the Java Pattern class.)

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.