I am a rookie in Regex for Ruby. I read some tutorials and evaluated a piece of code. Please let me know if I can do it in a better way.
Here is my text which needs to be split at {iwsection(*)} and {{usersection}}
t='{{iwsection(1)}}
This has some sample text 1 - line 1
This has some sample text 1 - line 2
{{iwsection(2)}}
This has some sample text 2
{{iwsection(3)}}
This has some sample text 3
{{usersection}}
This is a user section.
This has some sample text
This has some sample text'
Here is the ruby regex code I was able to manage.
t.split(/^({{[i|u][wsection]\w*...}})/)
Thank You.
The Desired Output : A array as,
[ '{{iwsection(1)}}', 'This has some sample text 1\nThis has some sample text 1 - line 2',
'{{iwsection(2)}}', 'This has some sample text 2',
'{{iwsection(3)}}', 'This has some sample text 3',
'{{usersection}}', 'This is a user section\nThis has some sample text\nThis has some sample text.']
With this I will build a Hash,
{
'{{iwsection(1)}}' => 'This has some sample text 1\nThis has some sample text 1 - line 2',
'{{iwsection(2)}}' => 'This has some sample text 2',
'{{iwsection(3)}}' => 'This has some sample text 3',
'{{usersection}}' => 'This is a user section\nThis has some sample text\nThis has some sample text.'
}
Edit: .....
The code.
section_array = text.chomp.split(/\r\n|\n/).inject([]) do |a, v|
if v =~ /{{.*}}/
a << [v.gsub(/^{{|}}$/, ""), []]
else
a.last[1] << v
end
a
end.select{ |k, v| (k.start_with?("iwsection") || k.start_with?("usersection")) }.map{ |k, v| ["{{#{k}}}", v.join("\n")] }