[ACCEPTED]-Java Regex remove new lines, but keep spaces.-regex
You don't have to use regex; you can use 2 trim()
and replaceAll()
instead.
String str = " \n a b c \n 1 2 3 \n x y z ";
str = str.trim().replaceAll("\n ", "");
This will give you the string 1 that you're looking for.
This will remove all spaces and newline 1 characters
String oldName ="2547 789 453 ";
String newName = oldName.replaceAll("\\s", "");
This will work:
str = str.replaceAll("^ | $|\\n ", "")
0
If you really want to do this with Regex, this 1 probably would do the trick for you
String str = " \n a b c \n 1 2 3 \n x y z ";
str = str.replaceAll("^\\s|\n\\s|\\s$", "");
Here is a pretty simple and straightforward 9 example of how I would do it
String string = " \n a b c \n 1 2 3 \n x y z "; //Input
string = string // You can mutate this string
.replaceAll("(\s|\n)", "") // This is from your code
.replaceAll(".(?=.)", "$0 "); // This last step will add a space
// between all letters in the
// string...
You could 8 use this sample to verify that the last 7 regex works:
class Foo {
public static void main (String[] args) {
String str = "FooBar";
System.out.println(str.replaceAll(".(?=.)", "$0 "));
}
}
Output: "F o o B a r"
More 6 info on lookarounds in regex here: http://www.regular-expressions.info/lookaround.html
This 5 approach makes it so that it would work 4 on any string input and it is merely one 3 more step added on to your original work, as 2 to answer your question accurately. Happy 1 Coding :)
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.