Search code examples
rubyregexrubymine

Regex to Replace Ruby Exception Handlers


I'm trying to find and replace all instances of exception handling for standard errors, e.g.:

begin
  ...
rescue StandardError => e
  logger.debug e.to_s
end

The answer here sounds like it should do what I want:

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

It led me to the following two possible regexes:

begin(.*?)rescue
(?<=begin)(.*?)(?=rescue)

Neither of these match anything. I'm not sure whether the problem is with the regexes or the IDE (Rubymine).

Suggestions? Thanks!


Solution

  • . does not match newline by default.

    Prepend (?s) or (?sm) in your regular expression to make dot(.) match newline. Or add s or sm switch.

    ?> "begin statements... rescue".scan /begin(.*?)rescue/
    => [[" statements... "]]
    >> "begin statements...\n rescue".scan /begin(.*?)rescue/
    => []
    >> "begin statements...\n rescue".scan /begin(.*?)rescue/s
    => []
    >> "begin statements...\n rescue".scan /begin(.*?)rescue/sm
    => [[" statements...\n "]]