Class SafeRegex

java.lang.Object
org.jline.utils.SafeRegex

public final class SafeRegex extends Object
Regex utilities that guard against catastrophic backtracking (ReDoS).

Java's java.util.regex engine uses backtracking, so patterns with nested quantifiers (e.g. (a+)+b) can take exponential time on non-matching input. This class wraps input in a CharSequence that enforces a wall-clock deadline, throwing RegexTimeoutException if matching takes too long.

Usage:

  • Field Details

    • DEFAULT_TIMEOUT_MS

      private static final long DEFAULT_TIMEOUT_MS
      Default timeout for regex matching operations.
      See Also:
    • CHECK_INTERVAL

      private static final int CHECK_INTERVAL
      How often (in charAt calls) the deadline is checked. Checking every call would add measurable overhead; checking every 1024 calls keeps the cost negligible while still catching runaway backtracking within milliseconds on typical input.
      See Also:
  • Constructor Details

    • SafeRegex

      private SafeRegex()
  • Method Details

    • matcher

      public static Matcher matcher(Pattern pattern, CharSequence input)
      Create a Matcher that will throw RegexTimeoutException if matching exceeds the default timeout.
    • matcher

      public static Matcher matcher(Pattern pattern, CharSequence input, long timeoutMs)
      Create a Matcher that will throw RegexTimeoutException if matching exceeds the given timeout. The timeout starts lazily on the first deadline check during matching (not when the Matcher is created), so it measures actual matching time.
    • matches

      public static boolean matches(Pattern pattern, CharSequence input)
      Test whether the pattern matches the entire input, with timeout protection. Returns false on timeout.
    • find

      public static boolean find(Pattern pattern, CharSequence input)
      Test whether the pattern is found anywhere in the input, with timeout protection. Returns false on timeout.
    • compileGlob

      public static Pattern compileGlob(String globPattern)
      Compile a glob-style pattern into a Pattern.

      Only * (match any string) and \ (escape) are special; every other character is regex-quoted so it matches literally. This is suitable for user-facing wildcard syntax where full regex power is not intended.

      Parameters:
      globPattern - the glob pattern (e.g. "foo*bar")
      Returns:
      a compiled regex pattern
    • compileGlob

      public static Pattern compileGlob(String globPattern, int flags)
      Compile a glob-style pattern into a Pattern with the given regex flags.
      Parameters:
      globPattern - the glob pattern
      flags - regex flags (e.g. Pattern.DOTALL)
      Returns:
      a compiled regex pattern
    • appendQuoted

      private static void appendQuoted(StringBuilder sb, char ch)