-3

I have got this far /( *)<pre ([^>]+)>([\s\S]*)<\/pre>/g but this fails with something like this:

<p>
  Hello
</p>
<p>
  World
</p>

$3 will be

  Hello
</p>
<p>
  World

What I want is

  Hello

Any help?

Before you downvote, I am not trying to manipulate the DOM with a regexp, I am writing tiny script that fixes the indentation.

kilianc
  • 7,397
  • 3
  • 26
  • 37
  • 7
    This is unlikely to be the right approach for whatever you're trying to do. (There's a famous StackOverflow answer on this subject: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454. It's written melodramatically, but there's definitely a solid core of truth in there.) – ruakh Nov 30 '15 at 03:02
  • Your problem is that your regex is greedy. You can add a `?` to most things regex to make them non-greedy `*` is greedy, `*?` is non-greedy. So `((.|[\n\r])*?)` should do the trick. ruakh is correct though! – ippi Nov 30 '15 at 03:14
  • The problem is that I am trying to do weird formatting si it has to be with regexp! @ippi `( *)
    ]+)>((.|[\n\r])*?)<\/pre>` works as expected, if you add it as answer I'll mark as correct
    – kilianc Nov 30 '15 at 03:18
  • Alright, what won't I do for them internet points? – ippi Nov 30 '15 at 03:24
  • I don't understand the downvotes, I am not trying to manipulate the DOM with a regexp, I writing tiny script that fixes indentation. – kilianc Nov 30 '15 at 08:57

1 Answers1

-1

Your problem is that your regex is greedy. You can add a ? to most things regex to make them non-greedy. * is greedy, *? is non-greedy. So ((.|[\n\r])*?) should do the trick. (ruakh is correct though!)

https://stackoverflow.com/a/2824314/1497533

Community
  • 1
  • 1
ippi
  • 9,857
  • 2
  • 39
  • 50
  • `((.|[\n\r])*?)` will do the trick, but it's technically incorrect (`\r` and `\n` are not the only line separator characters) and needlessly inefficient (using alternation where a character class will serve). `([\s\S]*?)` is what you should use. – Alan Moore Nov 30 '15 at 03:47