Java regex: newline + white space
Asked Answered
S

4

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
Strathspey answered 5/6, 2011 at 16:52 Comment(3)
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: download.oracle.com/javase/6/docs/api/java/util/regex/… ... If you are guaranteed that "line" is the first text on a given line, you could also try "\r?\n[^l]+".Aliform
@Mike M: Won't work on Apple's OSsOutbalance
Should work on OS-X though, right? Are people still using old versions of Apple?Aliform
A
10

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

Alamo answered 5/6, 2011 at 16:56 Comment(2)
1) The question says: _if you encounter line that begins with <blank> remove both the blank and the new line. 2) '\n' is not portableOutbalance
@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 :)Alamo
O
11
String res = orig.replaceAll("[\\r\\n]+\\s", "");
Outbalance answered 5/6, 2011 at 17:8 Comment(0)
A
10

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

Alamo answered 5/6, 2011 at 16:56 Comment(2)
1) The question says: _if you encounter line that begins with <blank> remove both the blank and the new line. 2) '\n' is not portableOutbalance
@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 :)Alamo
U
3

Perhaps to make it cross-platform:

String pattern = System.getProperty("line.separator") + " ";
string.replaceAll(pattern, "");
Uncover answered 5/6, 2011 at 17:2 Comment(1)
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 runningOutbalance
C
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.

Crackpot answered 5/6, 2011 at 17:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.