Is it possible to loop over multiple lines of text with RegEx and wrap each line in some contextual HTML?
I've become rather comfortable using RegEx in little javascript apps/plugins of mine but right now I wish that RegEx could save me a whole lot of time by doing the following:
I have a long text file that is formatted in the following manner:
Area which can contain spaces
Address which contains spaces and special characters
Phone Number
(empty line)
Area... (repeats the same structure as above)
Here is a short excerpt:
Ponsonby
114 Ponsonby Rd Open Til 3Am Friday & Saturday
09 3786466
Queen St
291 Queen St (Next to Bor Ders)
09 3090660
Sylvia Park
Sylvia Park Shopping Complex (286 Mt Wellington Highway)
09 5730100
I know need to wrap this in the following:
<li class="item">
<p class="phone">09 3786466</p>
<div class="location">
<strong>Ponsonby</strong>
<p class="address">114 Ponsonby Rd Open Til 3Am Friday & Saturday</p>
</div>
</li>
Is there any way I can run a RegEx to find each line info and the loop over my content wrapping things in this type of markup?
I am using TextMate by the way in case that matters.
So far my idea has been the following (which does not work):
([.\w\s]+)\n
([\w\s\b.]+)\n
([\d ]+)$\n
\n
And then in the replace part I would have my
<li class="item">
<p class="phone">$3</p>
<div class="location">
<strong>$1</strong>
<p>$2</p>
</div>开发者_开发知识库;
</li>
Any help would be much appreciated.
Thanks for reading.
Jannis
This tested function should do the trick:
function process_data(text)
{ // HTML-ify some data
var re = /(\S.*)\r?\n(\S.*)\r?\n([\d \-]+)(?=\r?\n[ ]*\r?\n|\s*$)/g;
var rep_str = "<li class=\"item\">\n" +
" <p class=\"phone\">$3</p>\n" +
" <div class=\"location\">\n" +
" <strong>$1</strong>\n" +
" <p>$2</p>\n" +
" </div>\n" +
"</li>\n";
return text.replace(re, rep_str);
}
精彩评论