rookie099
rookie099

Reputation: 2617

Remove substring with Ruby regular expression

I would like to use Ruby's sub(pattern, replacement) for removing a line of the form last-lrm-refresh=<value> from a multi-line substring. Here is an example of the entire string:

       maintenance-mode=true \
       last-lrm-refresh=1523448810 \
       no-quorum-policy=stop

The following does not quite work:

s.sub(' \\\n[ \t]+last-lrm-refresh=[0-9]+', '')

When I try the same regular expression in an interactive regular expression editor (such as Rubular) it works fine, so I guess the problem is about escaping characters.

What is the right form of regular expression to pass a string into sub to achieve the desired effect? I've tried a few "permutations" but without success so far. (I've also tried something similar with Perl before.)

Upvotes: 0

Views: 95

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

If you want to remove the line, it could be easier to support if you’ll be removing a line instead of regexping everything:

input = "maintenance-mode=true
       last-lrm-refresh=1523448810
       no-quorum-policy=stop"
input.split($/).reject do |line|
  line.strip.start_with?("last-lrm-refresh=")
end.join($/)
#⇒ maintenance-mode=true
#  no-quorum-policy=stop

Or, even easier for Ruby 2.4+, credits to @Stefan

input.each_line.grep_v(/(^\s*last-lrm-refresh=)/).join

Upvotes: 2

Related Questions