Regular expressions: how can I capture a block of text using regular expressions? (in ruby)

I am using ruby, and I am trying to find a way to capture text between {start_grab_entries} and {end_grab_entries} as follows:

{start_grab_entries}
i want to grab
the text that
you see here in
the middle
{end_grab_entries}

Something like that:

$1 => "i want to grab
       the text that
       you see here in
       the middle"

So far I have tried this as my regular expression:

\{start_grab_entries}(.|\n)*\{end_grab_entries}

However, using $ 1, this gives me a space. Do you know what I can do to correctly grab this block of text between tags?

+3
source share
3 answers

There is a better way to allow a dot to match newline strings ( /mmodifier):

regexp = /\{start_grab_entries\}(.*?)\{end_grab_entries\}/m

, * , ?, , .

, , , , ; ( a \n).

"", :

\{start_grab_entries\}((?:.|\n)*)\{end_grab_entries\}`

, , .

+6
string=<<EOF
blah
{start_grab_entries}
i want to grab
the text that
you see here in
the middle
{end_grab_entries}
blah
EOF

puts string.scan(/{start_grab_entries}(.*?){end_grab_entries}/m)
+1

, , , , . "" , , . , . , Ruby "flip-flop" ..:

#!/usr/bin/ruby

lines = []
DATA.each_line do |line|
  lines << line if (line['{start_grab_entries}'] .. line['{end_grab_entries}'])
end

puts lines          # << lines with boundary markers
puts
puts lines[1 .. -2] # << lines without boundary markers

__END__
this is not captured

{start_grab_entries}
i want to grab
the text that
you see here in
the middle
{end_grab_entries}

this is not captured either

:

{start_grab_entries}
i want to grab
the text that
you see here in
the middle
{end_grab_entries}

i want to grab
the text that
you see here in
the middle
0

Source: https://habr.com/ru/post/1767873/


All Articles