9

我有这个输入字符串(包含制表符、空格、换行符):


        That      is a test.              
    seems to work       pretty good? working.








    Another test  again.

[编辑]:我应该提供字符串以进行更好的测试,因为 stackoverflow 删除了所有特殊字符(制表符,...)

String testContent = "\n\t\n\t\t\t\n\t\t\tDas      ist ein Test.\t\t\t  \n\tsoweit scheint das \t\tganze zu? funktionieren.\n\n\n\n\t\t\n\t\t\n\t\t\t      \n\t\t\t      \n    \t\t\t\n    \tNoch ein  Test.\n    \t\n    \t\n    \t";

我想达到这个状态:


That is a test.
seems to work pretty good? working.
Another test again.

String expectedOutput = "Das ist ein Test.\nsoweit scheint das ganze zu? funktionieren.\nNoch ein Test.\n";

有任何想法吗?这可以使用正则表达式来实现吗?

replaceAll("\\s+", " ")不是我要找的。如果这个正则表达式将保留现有的 1 个换行符,那将是完美的。

我已经尝试过了,但这对我来说似乎不是最理想的......:

BufferedReader bufReader = new BufferedReader(new StringReader(testContent));
String line = null;
StringBuilder newString = new StringBuilder();
while ((line = bufReader.readLine()) != null) {
    String temp = line.replaceAll("\\s+", " ");
    if (!temp.trim().equals("")) {
        newString.append(temp.trim());
        newString.append("\n");
    }
}
4

5 回答 5

15

在单个正则表达式中(加上标签的小补丁):

input.replaceAll("^\\s+|\\s+$|\\s*(\n)\\s*|(\\s)\\s*", "$1$2")
     .replace("\t"," ");

正则表达式看起来令人生畏,但实际上可以很好地分解为这些经过 OR-ed 的部分:

  • ^\s+– 匹配开头的空格;
  • \s+$– 最后匹配空格;
  • \s*(\n)\s*– 匹配包含换行符的空格,并捕获该换行符;
  • (\s)\s*– 匹配空格,捕获第一个空格字符。

结果将与两个捕获组匹配,但一次可能只有一个组不为空。这允许我将匹配替换为"$1$2",这意味着“连接两个捕获组”。

唯一剩下的问题是我无法使用这种方法将制表符替换为空格,因此我通过简单的非正则表达式字符替换来解决这个问题。

于 2013-03-19T09:05:56.560 回答
6

分 4 个步骤:

text
    // 1. compress all non-newline whitespaces to single space
    .replaceAll("[\\s&&[^\\n]]+", " ")
    // 2. remove spaces from begining or end of lines
    .replaceAll("(?m)^\\s|\\s$", "")
    // 3. compress multiple newlines to single newlines
    .replaceAll("\\n+", "\n")
    // 4. remove newlines from begining or end of string
    .replaceAll("^\n|\n$", "") 
于 2013-03-19T09:00:32.573 回答
2

如果我理解正确,您只想用一个换行符替换一系列换行符。所以替换\n\n*\n(使用适当的标志)。如果行中有很多空格,只需^\s\s*$先删除空格(使用多行模式),然后替换换行符。

编辑:这里唯一的问题是一些换行符可能会保留在这里和那里,所以你必须小心首先折叠空格,然后修复空行问题。您可以将其进一步精简为可能的单个正则表达式,但使用这三个更容易阅读:

 Pattern spaces = Pattern.compile("[\t ]+");
 Pattern emptyLines = Pattern.compile("^\\s+$?", Pattern.MULTILINE);
 Pattern newlines = Pattern.compile("\\s*\\n+");
 System.out.print(
      newlines.matcher(emptyLines.matcher(spaces.matcher(
        input).replaceAll(" ")).replaceAll("")).replaceAll("\n"));
于 2013-03-19T08:45:48.503 回答
2

你为什么不做

String[] lines = split(s,"\n")
String[] noExtraSpaces = removeSpacesInEachLine(lines)
String result = join(noExtraSpaces,"\n")

不要忘记https://softwareengineering.stackexchange.com/questions/10998/what-does-the-jamie-zawinskis-quotation-about-regular-expressions-mean

于 2013-03-19T08:48:10.157 回答
2

首先用一个新行替换所有行,然后替换空格不是新行,最后,您应该从字符串的开头删除所有空格:

String test = "      This is              a real\n\n\n\n\n\n\n\n\n test !!\n\n\n   bye";
test = test.replaceAll("\n+", "\n");
test = test.replaceAll("((?!\n+)\\s+)", " ");
test = test.replaceAll("((?!\n+)\\s+)", "");

输出:

This is a real
test !!
bye
于 2013-03-19T08:49:24.083 回答