Java没有在字符串中看到空格

所以,我正在尝试解析一些包含多行文本的文本文件。 我的工作是仔细阅读所有文字并将其打印出来。

所以,我读了所有的行,我循环遍历它们并用空格分割每一行,如下所示:

line.split("\\s+");

现在,问题是在某些情况下Java没有看到两个单词之间的空格……

我也试图循环通过字符串有空间但Java没有看到它,而Character.isSpaceChar(char)返回true …

而现在我完全糊涂了……

这是代码:

 public void createMap(String inputPath, String outputPath) throws IOException { File f = new File(inputPath); FileWriter fw = new FileWriter(outputPath); List lines = Files.readAllLines(f.toPath(), StandardCharsets.UTF_8); for (String l : lines) { for (String w : l.split("\\s+")) { if (isNotRubbish(w.trim())) { fw.write(w.trim() + "\n"); } } } fw.close(); } private boolean isNotRubbish(String w) { Pattern p = Pattern.compile("@?\\p{L}+", Pattern.UNICODE_CHARACTER_CLASS); Matcher m = p.matcher(w); return m.matches(); } 

我怀疑你的文字字符与非破坏空间类似,而不是空格,因此无法通过\\s进行匹配。

在这种情况下,尝试使用\p{Zs}而不是\s

如http://www.regular-expressions.info/unicode.html中所述

\p{Zs}将匹配任何类型的空格字符

顺便说一句,如果你还想包括其他分隔符而不是像制表符\t或换行符那样的空格\r \n你可以将\p{Zs}\s结合起来像[\p{Zs}\s]