按新行拆分Java字符串 [英] Split Java String by New Line

查看:107
本文介绍了按新行拆分Java字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式将 JTextArea 中的文本拆分为 \ n 但是,这不起作用,我也试过 \\\\ n | \ r | n 和许多其他正则表达式的组合。
代码:

I'm trying to split text in a JTextArea using a regex to split the String by \n However, this does not work and I also tried by \r\n|\r|n and many other combination of regexes. Code:

public void insertUpdate(DocumentEvent e) {
    String split[], docStr = null;
    Document textAreaDoc = (Document)e.getDocument();

    try {
        docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset());
    } catch (BadLocationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    split = docStr.split("\\n");
}


推荐答案

这应该包括你:

String lines[] = string.split("\\r?\\n");

您只需要担心两个新行(UNIX和Windows)。

There's only really two newlines (UNIX and Windows) that you need to worry about.

这篇关于按新行拆分Java字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆