简体   繁体   中英

Why pipes are not deleted using “gsub” in Ruby?

I would like to delete from notes everything starting from the example_header . I tried to do:

example_header = <<-EXAMPLE
    -----------------
    ---| Example |---
    -----------------
EXAMPLE

notes = <<-HTML
    Hello World
    #{example_header}
    Example Here
HTML

puts notes.gsub(Regexp.new(example_header + ".*", Regexp::MULTILINE), "")

but the output is:

    Hello World
    ||

Why || isn't deleted?

The pipes in your regular expression are being interpreted as the alternation operator . Your regular expression will replace the following three strings:

"-----------------\n---"
" Example "
"---\n-----------------"

You can solve your problem by using Regexp.escape to escape the string when you use it in a regular expression ( ideone ):

puts notes.gsub(Regexp.new(Regexp.escape(example_header) + ".*",
                           Regexp::MULTILINE),
                "")

You could also consider avoiding regular expressions and just using the ordinary string methods instead ( ideone ):

puts notes[0, notes.index(example_header)]

Pipes are part of regexp syntax (they mean "or"). You need to escape them with a backslash in order to have them count as actual characters to be matched.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM