Library contents

Scala PatternSyntaxException

An unfinished character class causes the JVM regular-expression compiler to throw PatternSyntaxException.

A simple example

PatternSyntaxException

  1. Start with Pattern consisting of one open bracket
  2. Do this Compile the pattern
  3. Result Invalid pattern
The bracket begins a character class that never closes. Compiling detects the problem before a search.

Syntax

Scala syntax
Pattern.compile(rule)
Run these examples in Scala

Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.

scalac Lesson.scala
scala Lesson

Validate a saved product search

A store lets staff save a regular expression for product labels. A buyer leaves an opening bracket unfinished, so the search editor should highlight the invalid rule before it is saved.

ResultFix the search pattern
Lesson.scala
import java.util.regex.Pattern
import java.util.regex.PatternSyntaxException

object Lesson {
    def main(args: Array[String]): Unit = {
        try {
            Pattern.compile("[sale")
        } catch {
            case problem: PatternSyntaxException =>
                println("Fix the search pattern")
        }
    }
}
Output
Fix the search pattern

The bracket opens a character class that never closes. The editor asks the buyer to fix it.

Advertisements

Save a costume search

A costume librarian groups two rack prefixes in a character class. Compile the pattern before saving the search. An incomplete character class must go back to the editor.

Given[AB]
Worked resultPattern accepted

Catch a broken shelf filter

A clerk forgets the closing bracket in a saved shelf search. Compile the pattern before saving the search. An incomplete character class must go back to the editor.

Given[AB
Worked resultEdit pattern

What to watch for

Compile user-entered expressions before saving them. Plain label text can be passed to Pattern.quote.

Documentation for PatternSyntaxException