gpt4 book ai didi

java - 如何使用正则表达式删除以空格结尾的每个字符串行中的换行符? java

转载 作者:行者123 更新时间:2023-11-29 03:07:10 24 4
gpt4 key购买 nike

我逐行遍历一个文本文件,对于每一行,我检查该行是否“以空格和换行符结尾 \n”,然后我想取消该行打破并离开空间。

  • 一个例子:

假设我有一个包含以下文本的文本文件:

Hello World ,
这就是我。

注意:“Hello world”后有一个空格和一个换行符。

  • 预期结果:

Hello world,这是我。

这是我的代码:

String line;
while ((line = br.readLine()) != null) {
if (line.endsWith(" ")) {
bw.write(line.replaceFirst(" \n", " "));
}
}

正则表达式似乎不太好用。它匹配第一个空格而不考虑换行 \n 条件!有任何想法吗?我只想取消每个以空格结尾的字符串行中的换行符。

  • 注意:文本文件中没有明确显示换行符 \n!

最佳答案

根据我对你的问题的阅读,你似乎想改变这个:

A lineAnother line that ends with a space_Finally the end

(Where the _ represents a trailing space) into this:

A lineAnother line that ends with a space Finally the end

If that is the case, this should do it (assuming your bw is a BufferedWriter):

String line;
while ((line = br.readLine()) != null) {
/* We always write out the line (without an end-of-line character(s)) */
bw.write(line);

/* If the line does not end with a space, write out an end-of-line character */
if (!line.endsWith(" ")) {
bw.newLine();
}
}

更新:您要求解释为什么您的代码不起作用,这是您的代码:

/* 1 */ String line;
/* 2 */ while ((line = br.readLine()) != null) {
/* 3 */ if (line.endsWith(" ")) {
/* 4 */ bw.write(line.replaceFirst(" \n", " "));
/* 5 */ }
/* 6 */ }

第 1、5 和 6 行不需要解释。

  • 第 2 行:您向 BufferedReader 询问一行并检查返回的 String 是否不是 null。如果它是 null,那么您已经到达流的末尾。
  • 第 3 行:检查 line 是否以空格结尾。
  • 第 4 行:您在 line 上调用 replaceFirst 并将结果写入 bw,一个 BufferedWriter

问题:

  • 第 3 行:如果 line 以空格结尾,则您对 line 什么都不做。你根本不写出来。
  • 第 4 行:对 replaceFirst 的调用将永远不会执行任何操作,因为永远不会匹配 "\n"。关于这个问题本身和这个答案都有很多关于这一点的评论,但只是为了让你清楚: BufferedReader.readLine() 返回的 String > 将从不包含行尾字符,如the documentation for BufferedReader.readLine() 所述:

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

关于java - 如何使用正则表达式删除以空格结尾的每个字符串行中的换行符? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31573089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com