Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex: newline + white space

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
like image 228
MatteoSp Avatar asked Jun 05 '11 16:06

MatteoSp


People also ask

How to do white space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

What is\\ in regex?

To match a literal space, you'll need to escape it: "\\ " . This is a useful way of describing complex regular expressions: phone <- regex(" \\(? #

What is the regex for space in Java?

Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.

How do you remove new line and space from a string in Java?

Use String. trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.


1 Answers

String res = orig.replaceAll("[\\r\\n]+\\s", "");
like image 58
Op De Cirkel Avatar answered Sep 27 '22 17:09

Op De Cirkel