Search code examples
.netregexvb.netglobalektron

Global RegEx Replace Function to Create Html from Square Brackets []


I have some existing code that looks something like this:

[tag:cb cbid="12345" cbwidth="200" cbclassname="calloutbox" cbposition="left"] Lorem ipsum dolor sit amet, consectetur adipiscing elit.
[tag:cb cbid="123" cbwidth="200" cbclass="calloutbox2" cbposition="left"] Suspendisse eleifend enim a magna pretium porttitor.

I need to write a VB .Net global function that will match these [tag:cb] and take the optional parameters and rewrite the string with Html tags.

<div id="12345" width="200" class="calloutbox" position="left">content (based on id)</div>

Any help is appreciated. Thanks.


Solution

  • Here's a start:

    ^\[tag:cb([^\]]*)\](.*)$
    

    And then you use capturegroup 1 and 2 to make the new string:

    <div$1>$2</div>
    

    This will generate something like:

    <div cbid="12345" cbwidth="200" cbclassname="calloutbox" cbposition="left"> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
    <div cbid="123" cbwidth="200" cbclass="calloutbox2" cbposition="left"> Suspendisse eleifend enim a magna pretium porttitor.</div>
    

    The problem is that it will still have attributes like cbid="123" instead of id="123". Preferably you would like to run it through another regexp to replace all occurances of cb([^=]*) and replace with capturegroup 1.

    That would output the following:

    <div id="12345" width="200" classname="calloutbox" position="left"> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
    <div id="123" width="200" class="calloutbox2" position="left"> Suspendisse eleifend enim a magna pretium porttitor.</div>
    

    All you have to do now is to implement it in VB .Net :)

    You can see the first part in action here: http://regexr.com?2vbkq
    and the second part here: http://regexr.com?2vbl3