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,
It was safely removed only in the front and back.
Recommended Posts