在开头包含4个空格的行组

时间:2015-04-01 10:56:48

标签: java regex

我想在<pre>标记中包含开头有4个空格的所有行。

我尝试了什么?

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

DEMO

输入:

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

实际输出:

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

预期产出:

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

Java示例代码:

text.replaceAll(regex, "<pre>$1</pre>");

1 个答案:

答案 0 :(得分:1)

您可以使用:

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

RegEx Demo

<强>解释

(?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>