I am working on some legacy Java code and I see this statement:
Pattern lineWithCommentP2 = Pattern.compile("//(.[^<>]+?)(\\R|$)", Pattern.CASE_INSENSITIVE);
Matcher m = lineWithCommentP2.matcher(s);
s = m.replaceAll("<span class=\"cip\">//$1</span>$2");
As per the comment in the code, it is supposed to replace any line of text in the format
text1//text2
text3//text4
with
text1<span class="cip">//text2</span>
text3<span class="cip">//text4</span>
However, while testing it, I see that it is replacing the original line with
text1<span class="cip">//text2
</span>
text3<span class="cip">//text4
</span>
(It is adding a new line after text2 and text4).
I am not able to tweak the regex to avoid that extra line break. Any idea why and how can I fix it?
thank you.
ADDED THE FOLLOWING : To reproduce, create a text file with this data:
<p>test statement </p>
<pre class="code">public class TestClass{
public static void main(String[] args){
statement1; //1
stement2(); //2
}
}
</pre>
<p>test stmt</p>
Then run the following code :
byte[] ba = Files.readAllBytes(Paths.get("c:\\temp\\test.txt"));
String s = new String(ba);
Pattern lineWithCommentP2 = Pattern.compile("//(.[^<>]+?)(\\R|$)", Pattern.CASE_INSENSITIVE);
Matcher m = lineWithCommentP2.matcher(s);
s = m.replaceAll("<span class=\"cip\">//$1</span>$2");
Files.write(Paths.get("c:\\temp\\test2.txt"), s.getBytes(), StandardOpenOption.CREATE);
This generates the following content in test2.text:
<p>test statement </p>
<pre class="code">public class TestClass{
public static void main(String[] args){
statement1; <span class="cip">//1
</span>
stement2(); <span class="cip">//2
</span>
}
}
</pre>
<p>test stmt</p>