JavaScript Regex to match any words within nested square brackets?
<p>I'm trying to find a way to use regex to make text italic inside of square <code>[]</code> brackets, inclusive of nested square brackets, but not the brackets themselves.  So far the best I've come up with is:</p>

<pre><code>text = text.replace(/(\[+)([^\[\]]+)(]+)/g, '$1&lt;span style="font-style: italic;"&gt;$2&lt;/span&gt;$3');
</code></pre>

<p>however that fails in the case of nested brackets, something like:</p>

<pre><code>[test1] test2 ([[readonly ][optionality ][argumentType ]argumentName[ = defaultValue]]...) [test3] test4
</code></pre>

<p>Should parse to:</p>

<p>[<em>test1</em>] test2 ([[<em>readonly</em> ][<em>optionality</em> ][<em>argumentType</em> ]<em>argumentName</em>[ <em>= defaultValue</em>]]...) [<em>test3</em>] test4</p>

<p>But instead the above regex produces:</p>

<p>[<em>test1</em>] test2 ([[<em>readonly</em> ][<em>optionality</em> ][<em>argumentType</em> ]argumentName[ <em>= defaultValue</em>]]...) [<em>test3</em>] test4</p>

<p>(with the text <code>argumentName</code> normal instead of italics)</p>