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}.+?)<br />", "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.
\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.
The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.
The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.
"\n" matches a newline character.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With