Search code examples
regexiosregexkitlite

Parsing with regular expressions


I have some text like

some text [http://abc.com/a.jpg] here will be long text 

can be multiple line breaks again [http://a.com/a.jpg] here will be other text

blah blah

Which I need to transform into

<div>some text</div><img src="http://abc.com/a.jpg"/><div>here will be long text 

can be multiple line breaks again</div><img src="http://a.com/a.jpg"/><div>here will be other text

blah blah</div>

To get the <img> tags, I replaced \[(.*?)\] with <img src="$1"/>, resulting in

some text<img src="http://abc.com/a.jpg"/>here will be long text 

can be multiple enters again<img src="http://a.com/a.jpg"/>here will be other text

blah blah

However, I have no idea how to wrap the text in a <div>.

I'm doing everything on the iPhone with RegexKitLite


Solution

  • Here's the simplest approach:

    1. Replace all occurrences of \[(.*?)\] with </div><img src="$1"/><div>
    2. Prepend a <div>
    3. Append a </div>

    That does have a corner case where the result starts or ends with <div></div>, but this probably doesn't matter.

    If it does, then:

    1. Replace all occurrences of \](.*?)\[ with ]<div>$1</div>[
    2. Replace all occurrences of \[(.*?)\] with <img src="$1"/>