简体   繁体   English

.replaceAll和换行符的java问题

[英]java problems with .replaceAll and newline

So this code works as expected: 因此,此代码按预期工作:

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

output: 输出:

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

But I am reading in an email with javamail and for some reason when I look at the message it has a bunch of newlines in it. 但是我正在阅读带有javamail的电子邮件,由于某种原因,当我查看该消息时,其中包含很多换行符。 But for some reason replaceAll("\\n"," ") isn't working for me. 但是由于某种原因,replaceAll(“ \\ n”,“”)对我不起作用。 I wonder if it is an encoding issue or something. 我想知道这是编码问题还是其他问题。 Is there another way to have a newline? 有换行的另一种方法吗? When I look at the email under gmail it doesn't seem to have any newlines but when I print it out or try to export the message then any line with more than about 70 characters gets split up on a word boundary. 当我查看gmail下的电子邮件时,它似乎没有换行符,但是当我将其打印出来或尝试导出邮件时,则任何超过70个字符的行都会在单词边界处分开。 Any ideas? 有任何想法吗?

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);
}

output: 输出:

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.

It seems that lines are not separated with \\n but with \\r\\n . 似乎行不是用\\n隔开,而是用\\r\\n隔开。 Consider using 考虑使用

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

or 要么

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

to accept also \\r\\n \\n \\r . 也接受\\r\\n \\n \\r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM