0

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.)

3
  • 5
    s.sub(/ \\\n[ \t]+last-lrm-refresh=[0-9]+/, '') - use a regex, not a literal string substitution. Commented Jun 15, 2018 at 9:05
  • 1
    ' \\\n[ \t]+last-lrm-refresh=[0-9]+' is not a regular expression. It's a string. Commented Jun 15, 2018 at 9:06
  • 1
    I suggest closing as a typo. Can't find a good dupe. Commented Jun 15, 2018 at 9:07

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

7 Comments

Or something like input.each_line.grep_v(/last-lrm-refresh=/).join
Thx. The thing is that last_lrm-refresh=... may appear in the last line, in which case I'd also like to remove the previous /\\\n/. That's why the regex-based approach came to mind.
I am not sure I follow. My code effectively removes the whole line.
@rookie099 just chomp it afterwards. The fact that the last "line" isn't a proper line should not make you jump through hoops.
@Stefan: ...or easier with input.each_line.grep_v(/(^\s*last-lrm-refresh=)/).join.chomp. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.