gpt4 book ai didi

java .replaceAll 和换行符问题

转载 作者:行者123 更新时间:2023-12-01 23:14:47 27 4
gpt4 key购买 nike

所以这段代码按预期工作:

String test = "ONE: this is a\ntest string.";
System.out.println(test);
test = test.replaceAll("\n", " ");
System.out.println(test);

输出:

ONE: this is a 
test string.
ONE: this is a test string.

但是我正在使用 javamail 阅读一封电子邮件,由于某种原因,当我查看该消息时,其中有一堆换行符。但由于某种原因,replaceAll("\n","") 对我不起作用。我想知道这是编码问题还是其他问题。还有另一种方法可以换行吗?当我在 gmail 下查看电子邮件时,它似乎没有任何换行符,但是当我打印出来或尝试导出邮件时,任何超过 70 个字符的行都会在单词边界上分开。有什么想法吗?

Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "xxx@gmail.com", "password");

Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_WRITE);
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message messages[] = inbox.search(ft);
for(Message msg:messages) {
String message = mailman.getContent(msg);
System.out.println("ONE:"+ message);
message = message.replaceAll("\n","");
System.out.println("TWO: "+message);
}

输出:

ONE: We just wanted to remind you about the start of our Underclassmen Academy. 
This program is intended for all freshmen and sophomores who are in the
initial stages of your career preparation. Juniors are also invited to attend
if you'd like to gain more exposure and/or are still recruiting.

TWO: We just wanted to remind you about the start of our Underclassmen Academy.
This program is intended for all freshmen and sophomores who are in the
initial stages of your career preparation. Juniors are also invited to attend
if you'd like to gain more exposure and/or are still recruiting.

最佳答案

看起来行不是用\n分隔的,而是用\r\n分隔的。考虑使用

replaceAll("\r\n"," ")

replaceAll("\r?\n|\r"," ")

也接受\r\n \n \r

关于java .replaceAll 和换行符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21420497/

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