java修剪字符串中的所有“空格”
我正在解析一个PDF文件,并得到许多带有\t, \r, \n,\s
的字符串。。。它们出现在字符串的两端,并且不按顺序出现。这样我就可以拥有
例如:
“\t\s\t\n
我需要的一些重要数据被无用数据包围\r\t\s\s\r\t\t
”
.有什么有效的方法来修剪这些线吗?
到目前为止,我所拥有的还不够好,因为我需要一些符号
public static String trimToLetters(String sourceString) {
int beginIndex = 0;
int endIndex = sourceString.length() - 1;
Pattern p = Pattern.compile("[A-Z_a-z\\;\\.\\(\\)\\*\\?\\:\\\"\\']");
Matcher matcher = p.matcher(sourceString);
if (matcher.find()) {
if (matcher.start() >= 0) {
beginIndex = matcher.start();
StringBuilder sb = new StringBuilder(sourceString);
String sourceReverse = sb.reverse().toString();
matcher = p.matcher(sourceReverse);
if (matcher.find()) {
endIndex = sourceString.length() - matcher.start();
}
}
}
return sourceString.substring(beginIndex, endIndex);
}
# 1 楼答案
String
的trim
方法应该能够删除字符串两端的所有空白:p.S.
\s
在Java中不是有效的转义序列