有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    Stringtrim方法应该能够删除字符串两端的所有空白:

    trim: Returns a copy of the string, with leading and trailing whitespace omitted.

    p.S.\s在Java中不是有效的转义序列