因此,此代码按预期工作:
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
。