RegexpError
RubyERRORNotableRegex

Invalid regular expression

Quick Answer

Validate user-supplied regex patterns with Regexp.new inside a rescue block before using them.

What this means

Raised when a regular expression pattern is syntactically invalid and cannot be compiled. This occurs at Regexp.new or when using a dynamic regex with a bad pattern string.

Why it happens
  1. 1Unmatched or unescaped parentheses in the regex pattern
  2. 2Invalid quantifier (e.g., {3,1} where min > max)
  3. 3User-supplied patterns that contain syntax errors

Fix

Validate dynamic patterns safely

Validate dynamic patterns safely
def safe_regex(pattern)
  Regexp.new(pattern)
rescue RegexpError => e
  puts "Invalid pattern: #{e.message}"
  nil
end

Why this works

Wrapping Regexp.new in a rescue ensures a bad user-supplied pattern returns nil instead of crashing.

Code examples
Reproducing the errorruby
Regexp.new('(unclosed')
# RegexpError: premature end of char-class: /(unclosed/
Dynamic pattern from user inputruby
pattern = params[:search]
re = Regexp.new(Regexp.escape(pattern))   # escape untrusted input
Rescue RegexpErrorruby
begin
  re = Regexp.new(user_pattern)
  results = data.grep(re)
rescue RegexpError
  results = []
end
Sources
Official documentation ↗

Ruby Core Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Ruby errors