Remove consecutive line breaks and tabs before and after in Java

Postscript I noticed that one character does not match From " ^ [\ t \ n] * ([^ \ t \ n] + (. | \\ s) * [^ \ t \ n] +) [\ t \ n] * $ " Fixed to " ^ [\ t \ n] * ([^ \ t \ n] * (. | \\ s) * [^ \ t \ n] +) [\ t \ n] * $ ". The first plus became an asterisk.


I hate regular expressions. The point is to leave line breaks and tabs other than before and after. I'm really into it, so I'll write an article.


    public static String trimNewline(String str) {
        String regex = "^[\t\n]*([^\t\n]*(.|\\s)*[^\t\n]+)[\t\n]*$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        if (m.find()) {
            return m.group(1);
        } else { //"Empty string" and "character string consisting only of tabs and line breaks" do not match and come here
            return "";
        }
    }

Looking at Java regular expressions

System.out.println(trimNewline("\t\n\t\nhoge\t\n\t\n")); // hoge
System.out.println(trimNewline("\t\n\t\nhoge")); // hoge
System.out.println(trimNewline("hoge\t\n\t\n")); // hoge

Also, there are line breaks and tabs in the middle, "\t\n\n\n\t\tho\t\t\nhoge\nge\t\n\t\n" me too, image.png

It was safely removed only in the front and back.

Recommended Posts

Remove consecutive line breaks and tabs before and after in Java
Line breaks in the entered text are not displayed in view
Remove consecutive line breaks and tabs before and after in Java
In fact, Ruby distinguishes between line breaks and whitespace.
Encoding and Decoding example in Java
StringBuffer and StringBuilder Class in Java
Remove "assets" and "turbolinks" in "Rails6".
Understanding equals and hashCode in Java
Hello world in Java and Gradle
Difference between final and Immutable in Java
[Java] for Each and sorted in Lambda
Program PDF headers and footers in Java
Java to C and C to Java in Android Studio
Reading and writing gzip files in Java
Difference between int and Integer in Java
Discrimination of Enums in Java 7 and above
[Java] [POI] Create a table in Word and start a new line in one cell