I'm trying to wrap all lines that are prefixed with 4 space chars with pre
tags. This is what I have so far
Text = Text.replace(new RegExp("( {4}.+?)<b开发者_开发技巧r />", "g"), "$1\n");
Text = Text.replace(new RegExp("( {4}.+?)\n", "g"), "<pre class=\"brush: js;\">$1</pre>");
It works but it wraps every line in a pre
. I need it to wrap the whole block.
Maybe something like this would work? It matches multiple lines in a row..
( {4}.*(\n {4}.*)*)\n
Do you really need to do this with regular expressions? Regexes are cool and useful but they're not the only tool in your toolbox and sometimes it is best to do something straight forward and move on to real problems. I'd just bust it into lines and parse it line-by-line with an accumulator for the things that need to be pre-ified:
var lines = text.split('\n');
var pre = [ ];
var out = [ ];
for(var i = 0; i < lines.length; ++i) {
if(lines[i].match(/^ /)) {
pre.push(lines[i]);
}
else if(pre.length > 0) {
out.push('<pre>' + pre.join('\n') + '</pre>' + '\n');
out.push(lines[i]);
pre = [ ];
}
else {
out.push(lines[i]);
}
}
if(pre.length > 0) {
out.push('<pre>' + pre.join('\n') + '</pre>' + '\n');
}
text = out.join('\n');
That may not be as clever as an incomprehensible regex but at least you'll be able to understand what it is doing six months down the road.
http://jsfiddle.net/ambiguous/tFNyv/
Please try:
Text = Text.replace(new RegExp("(( {4}.+?\n)+)", "g"), "<pre class=\"brush: js;\">$1</pre>");
Assuming the
replacement has already been done.
It worked for:
lalalal
noway it's block1
greetings
foobar
block2
indeed block2
And produced, line breaks are hidden :
<pre class="brush: js;"> lalalal
noway it's block1
greetings
</pre>
<pre class="brush: js;"> foobar
block2
indeed block2
</pre>
Try with:
$.each(text.split('\n'), function(index, value)
{
var t = value.replace(/^[\s]{4}(.*)$/, "<pre>$1</pre>");
$("body").append(t);
});
http://jsfiddle.net/jotapdiez/zx8Pg/
It sounds like the questioner wants to do a markdown-like conversion. This question is similar to this one: How do I fix this multiline regular expression in Ruby?. If the desired effect is to mimic markdown code conversion, consider the following (adapted from my accepted answer to the ruby question):
var re = /(\r?\n)((?:(?:\r?\n)+(?:[ ]{4}|\t).*)+\r?\n)(?=\r?\n)/mg;
text = text.replace(re, '$1<pre class="brush: js">$2</pre>');
精彩评论