16

should be simple, but I'm going crazy with it.

Given a text like:

line number 1
line number 2
 line number 2A
line number 3
 line number 3A
 line number 3B
line number 4

I need the Java regex that deletes the line terminators then the new line begin with space, so that the sample text above become:

line number 1
line number 2line number 2A
line number 3line number 3Aline number 3B
line number 4
MatteoSp
  • 2,940
  • 5
  • 28
  • 36
  • 1
    Try `"\r?\n\W+"`. I haven't tried it, so I don't want to register it as an answer. In case you haven't checked it out already, you can find some specifics about Java regex here: http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html ... If you are guaranteed that "line" is the first text on a given line, you could also try `"\r?\n[^l]+"`. – Mike M Jun 05 '11 at 16:59
  • @Mike M: Won't work on Apple's OSs – Op De Cirkel Jun 05 '11 at 17:04
  • Should work on OS-X though, right? Are people still using old versions of Apple? – Mike M Jun 05 '11 at 18:28

4 Answers4

11
String res = orig.replaceAll("[\\r\\n]+\\s", "");
Op De Cirkel
  • 28,647
  • 6
  • 40
  • 53
10

yourString.replaceAll("\n ", " "); this wont help?

dantuch
  • 9,123
  • 6
  • 45
  • 68
  • 3
    1) The question says: _if you encounter line that begins with remove both the blank and the new line. 2) '\n' is not portable – Op De Cirkel Jun 05 '11 at 17:00
  • 3
    @MatteoSp, remeber that Stings are immutable, so in fact you need `yourString = yourString.replaceAll("\n ", " ");` or something like that, because calling method wont change String object itself permanently. Glad to help :) – dantuch Jun 05 '11 at 17:34
3

Perhaps to make it cross-platform:

String pattern = System.getProperty("line.separator") + " ";
string.replaceAll(pattern, "");
gouki
  • 4,382
  • 3
  • 20
  • 20
  • 7
    Well, the system `line.separator` doesn't really help, since you don't know if the files were created on the system where the JVM is running – Op De Cirkel Jun 05 '11 at 17:46
2

"\n " This is should do the trick if you are in Unix LF mode. For DOS like you need to match CRLF "\r\n ". Did check with RegexBuddy looking fine.

millebii
  • 1,277
  • 2
  • 17
  • 27