0

I've ran into a bit of a rough spot in this Java program I'm writing an thought I would ask for some help. I'm using regex to replace certain lines in a file being read in and not getting the desired result. I want to replace all series of 3 new lines in my file and thought this would be straight forward since my regex is working in notepad++ but I guess not. Below is what an example of what the file is like:

FIRST SENTENCECRLF
CRLF
CRLF
CRLF
CRLF
CRLF
SECOND SENTENCECRLF

So, in other words, I am wanting to remove 3 of those carriage return\line feed instances between the first and second sentence lines. Below is what I've tried so far. The first tried in Java results in no change to the file (works in Notepad++ fine). The second, pretty much the same as the first works in notepad++ but not Java. The third is pretty much the exact same case as the other two. Anyone have any helpful suggestions as to what might work in this situation. At this point anything would be greatly appreciated!

^(\r\n){3}

^\r\n(\r\n)(\r\n)

^\r\n\r\n\r\n
Tastybrownies
  • 897
  • 3
  • 23
  • 49
  • 1
    Why you put `^` (beginning of line) in your regex ? For java, the entire files is one string, `^` would translate the beginning of the string. If your file text been put entirely into string, then `^` equals the beginning of the file. – Ferdinand Neman Sep 03 '15 at 02:55
  • Hmmmm, I do see what you mean and it makes sense. So I reduced it to \n\r\n\r\n\r\n and this seems to do a little bit better but takes away an extra line. I will have to ensure that one line is not combined with a previous one. Thanks! – Tastybrownies Sep 03 '15 at 03:14

1 Answers1

1

Try the following regex:

(?m)^(\r\n){3}

The (?m) enables multi-line mode in Java, as explained in How to use java regex to match a line

Community
  • 1
  • 1
Iceberg
  • 376
  • 1
  • 12