2

I want to enclose all the lines in <pre> tag that have 4 spaces in the beginning.

What I have tried?

^[ ]{4}(.*)(?!=^[ ]{4})

DEMO

Input:

Here is the code:
    String name = "Jon";
    System.out.println("Hello "+name);
output:
    Hello Jon

Actual output:

Here is the code: 
    <pre>String name = "Jon";</pre> 
    <pre>System.out.println("Hello "+name);</pre>
output: 
    <pre>Hello Jon</pre> 

Expected output:

Here is the code:
<pre>
    String name = "Jon";
    System.out.println("Hello "+name);
</pre>
output:
<pre>
    Hello Jon
</pre>

Java sample code:

text.replaceAll(regex, "<pre>$1</pre>");
Braj
  • 46,415
  • 5
  • 60
  • 76

1 Answers1

1

You can use:

String out = input.replaceAll("(?m)((?:^ {4}\\S.*$\\r?\\n)*^ {4}\\S.*$)", 
                              "<pre>\\n$1\\n</pre>");

RegEx Demo

Explanation:

(?m)                    # enable multilie mode
^ {4}\\S.*$             # match a line with exact 4 spaces at start
\\r?\\n                 # followed by a line feed character
(?:^ {4}\\S.*$\\r?\\n)* # match 0 or more of such lines
^ {4}\\S.*$             # followed by a line with exact 4 spaces at start
<pre>\\n$1\\n</pre>     # replace by <pre> newline matched block newline </pre>
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Thank let me try to understand it. – Braj Apr 01 '15 at 11:13
  • Added an explanation of regex and of course regex101 demo link also has some details. – anubhava Apr 01 '15 at 11:16
  • that last part `^ {4}\\S.*$ ` is not understood. Why there is no negative look around? why `^ {4}\\S.*$ ` is needed? – Braj Apr 01 '15 at 11:19
  • oh there is no lookahead. Last part is `^ {4}\\S.*$` which is matching last such line **without** a newline so that we can avoid adding 2 newlines before `` otherwise regex can be simplified to: `(?m)((?:^ {4}\\S.*$\\r?\\n?)+` also. – anubhava Apr 01 '15 at 11:20
  • Yes you can sure ask as many, I will be offline for couple of hours due to some work but will answer all the queries once I come back online. – anubhava Apr 01 '15 at 11:31