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/
source share