Please do not use bbcode. This evil.
BBCode came to life when developers were too lazy to parse HTML properly and decided to invent their own markup language. Like all laziness products, the result is completely inconsistent, non-standard and widely accepted.
Try using a more user-friendly markup language like Markdown (which uses stack overflow) or Textile . Both have parsers for Ruby:
If you still do not want to follow my advice and want to go with BBCode, do not reinvent the wheel and use the BBCode parser . To answer your question directly, there is the least desirable option: use a regular expression.
/\[img\].*?\[\/img\]/
As seen on rubular . Although I would use /\[img\](.*?)\[\/img\]/ , so it will extract the contents inside the img tags. Note that this is pretty fragile and breaks if there are nested img tags. Therefore, the advice is to use a parser.
source share