How to remove newlines from beginning and end of a string?
Use String.trim()
method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.
String trimmedString = myString.trim();
Remove end of line characters from end of Java String
You can use s = s.replaceAll("[\r\n]+$", "");
. This trims the \r
and \n
characters at the end of the string
The regex is explained as follows:
[\r\n]
is a character class containing\r
and\n
+
is one-or-more repetition of$
is the end-of-string anchor
References
- regular-expressions.info/Anchors, Character Class, Repetition
Related topics
You can also use String.trim()
to trim any whitespace characters from the beginning and end of the string:
s = s.trim();
If you need to check if a String
contains nothing but whitespace characters, you can check if it isEmpty()
after trim()
:
if (s.trim().isEmpty()) {
//...
}
Alternatively you can also see if it matches("\\s*")
, i.e. zero-or-more of whitespace characters. Note that in Java, the regex matches
tries to match the whole string. In flavors that can match a substring, you need to anchor the pattern, so it's ^\s*$
.
Related questions
- regex, check if a line is blank or not
- how to replace 2 or more spaces with single space in string and delete leading spaces only
Related Topics
Launching Spring Application Address Already in Use
Java.Sql.Sqlexception: Field Doesn't Have a Default Value
Setting Default Values to Null Fields When Mapping With Jackson
How to Clean Project Cache in Intellij Idea Like Eclipse'S Clean
Rounded Swing Jbutton Using Java
How to Unpackage and Repackage a War File
Using Loop to Accept Additional User Input Until User Enters a Value That Ends the Input
Java Generics Incompatible Types (No Instance(S) of Type Variable(S) Exist)
Removing a Column in Java from a 2D Array
How to Persist a Property of Type List<String> in Jpa
How to Store Original Date/Time Without Timezone Calculation to Mongodb
How to Count Method Calls by Instance
How to Read Empty Cells of an Excel File Using Poi
In Junit 5, How to Run Code Before All Tests
How to Select One Object from the List of Objects
How to Solve Gradle Error Cannot Find Symbol
How to Query Dynamodb Based on Partition Key and Sort Key [Java]