Regex to split BBCode into pieces

ghz 1years ago ⋅ 119 views

Question

I have this:

str = "some html code [img]......[/img] some html code [img]......[/img]"

and I want to get this:

["[img]......[/img]","[img]......[/img]"]

Answer

irb(main):001:0> str = "some html code [img]......[/img] some html \
code [img]......[/img]"
"some html code [img]......[/img] some html code [img]......[/img]"
irb(main):002:0> str.scan(/\[img\].*?\[\/img\]/)
["[img]......[/img]", "[img]......[/img]"]

Keep in mind that this is a very specific answer that is based on your exact question. Change str by, say, adding an image tag within an image tag , and [all Hell will break loose](https://stackoverflow.com/questions/1732348/regex-match-open-tags- except-xhtml-self-contained-tags/1732454#1732454).