how can I copy the text in range between ‘def’ and ‘end’, which are
test = 100;
puts test
(1…10).each { |i| puts i }
into a variable.
I’ve tried using ~/def … ~/end but not matched
This is one way that solves what you said. The problem with regexes is
how it will handle the cases you didn’t say
(for example, what do you want to match when there are more “ends” and
so on).
irb(main):002:0> text =<<EOF
irb(main):003:0" def
irb(main):004:0" test = 100;
irb(main):005:0" puts test
irb(main):006:0" (1…10).each { |i| puts i }
irb(main):007:0" end
irb(main):008:0" EOF
=> “def\n test = 100;\n puts test\n (1…10).each { |i| puts i
}\nend\n”
irb(main):011:0> m = text.match /def(.*)end/m
=> #<MatchData “def\n test = 100;\n puts test\n (1…10).each { |i|
puts i }\nend” 1:“\n test = 100;\n puts test\n (1…10).each { |i|
puts i }\n”>
irb(main):012:0> m[1]
=> “\n test = 100;\n puts test\n (1…10).each { |i| puts i }\n”
This is one way that solves what you said. The problem with regexes is
how it will handle the cases you didn’t say
(for example, what do you want to match when there are more “ends” and
so on).
irb(main):002:0> text =<<EOF
irb(main):003:0" def
irb(main):004:0" test = 100;
irb(main):005:0" puts test
irb(main):006:0" (1…10).each { |i| puts i }
irb(main):007:0" end
irb(main):008:0" EOF
=> “def\n test = 100;\n puts test\n (1…10).each { |i| puts i
}\nend\n”
irb(main):011:0> m = text.match /def(.*)end/m
=> #<MatchData “def\n test = 100;\n puts test\n (1…10).each { |i|
puts i }\nend” 1:"\n test = 100;\n puts test\n (1…10).each { |i|
puts i }\n">
irb(main):012:0> m[1]
=> “\n test = 100;\n puts test\n (1…10).each { |i| puts i }\n”
Hope this helps,
Jesus.
Thank you, it did helped me.
Actually I’ve tried using the same regex as you use, which is
/def(.*)end/, however i overlooked the m in the end of /
Thank you