Match all lines with four spaces

I am trying to wrap all lines with a 4 space prefix with pre tags. This is what I still have

 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 each line in pre . I need this to wrap the whole block.

+6
source share
5 answers

Maybe something like this will work? It matches multiple lines in a row.

 ( {4}.*(\n {4}.*)*)\n 
+3
source

Do you really need to do this with regular expressions? Regulars are cool and useful, but they are not the only tool in your toolbox, and sometimes it’s best to do something directly and go to real problems. I would just put it in the lines and take it apart in turn with the battery for things that need to be foreseen:

 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'); 

It may not be as smart as an incomprehensible regular expression, but at least you can understand what it does in six months.

http://jsfiddle.net/ambiguous/tFNyv/

+3
source

Try:

 Text = Text.replace(new RegExp("(( {4}.+?\n)+)", "g"), "<pre class=\"brush: js;\">$1</pre>"); 

Assume the replacement
already done.

He worked for:

  lalalal noway it block1 greetings foobar block2 indeed block2 

And created, line breaks are hidden:

 <pre class="brush: js;"> lalalal noway it block1 greetings </pre> <pre class="brush: js;"> foobar block2 indeed block2 </pre> 
+1
source

Try:

 $.each(text.split('\n'), function(index, value) { var t = value.replace(/^[\s]{4}(.*)$/, "<pre>$1</pre>"); $("body").append(t); }); 

http://jsfiddle.net/jotapdiez/zx8Pg/

0
source

It seems that the questionnaire wants to do a similar markdown conversion. This question is similar to this: How to fix this multi-line regular expression in Ruby? . If the desired effect is to mimic the 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>'); 
0
source

Source: https://habr.com/ru/post/887032/


All Articles