# Regexp'n bbcode

**URL:** <https://www.ruby-forum.com/t/regexpn-bbcode/158486>\
**Category:** Ruby\
**Created:** [January 23, 2009, 9:11pm UTC](https://www.ruby-forum.com/t/regexpn-bbcode/158486 "2009-01-23T21:11:33Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![morbusg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/8dc957/32.png) [@morbusg](https://www.ruby-forum.com/u/morbusg)\
**Post date:** [January 23, 2009, 9:11pm UTC](https://www.ruby-forum.com/t/regexpn-bbcode/158486/1 "2009-01-23T21:11:33Z")

</div>

I’m scratching my head over the goal of converting bbcode to markdown.  
The gist of the problem boils down to handling regexp matches inside  
regexp matches.

Example: bbcode:

> [@](#):
>
> [quote=“bar”]baz[/quote]diu

which I’d like to convert to:

> foo:
> 
> > bar:  
> > baz  
> > diu

What I’ve got so far is something like this:

START = ‘[quote’  
IDENT = ‘(?::\w+)?’  
USER = ‘(?:="([\w -\_]+)")?’  
STOP = “\[\/quote#{IDENT}\]”  
QUOTE = “#{START+IDENT+USER}\]”  
INSIDEQUOTE = /#{QUOTE}(.+?)(?!#{START})#{STOP}/m

def bbcode2markdown(txt)  
@quotedusers = {}  
txt.scan(/#{START}/).each\_with\_index { |match,index|  
txt.gsub!(INSIDEQUOTE) { |str| $2.gsub(/^(.)/, ‘\>\1’).gsub(/(.)$/,  
“\n\1\n”) }  
depth = ‘\>’ \* (index + 1)  
if $1  
@quotedusers[depth] = $1  
end  
}

```
@quotedusers.each { |depth,user|
  txt.sub!(/^#{depth}(\w)/, "#{depth} **#{user}** : \\1")
}

```

end

But I am missing some cases for some reason, and my brain is melting  
merely at looking at that code after a couple of months after writing  
it.  
I’m sure there must be a straight-forward way to get this done, but my  
melted brain just can’t figure out how.

(re-posted after a mistake, sorry about that rforum)
