views:

13265

answers:

5

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");
}
+11  A: 

This should cover you:

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

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

cletus
A JTextArea document SHOULD use only '\n'; its Views completely ignore '\r'. But if you're going to look for more than one kind of separator, you might as well look for all three: "\r?\n|\r".
Alan Moore
This worked well thank you.
dr.manhattan
+1  A: 

If you don’t want empty lines:

String.split("[\\r\\n]+")
Gumbo
+2  A: 

The above code doesnt actually do anything visible - it just calcualtes then dumps the calculation. Is it the code you used, or just an example for this question?

try doing textAreaDoc.insertString(int, String, AttributeSet) at the end?

Chii
insertUpdate() is a DocumentListener method. Assuming the OP is using it right, trying to modify the document from within the listener method will generate an exception. But you're right: the code in that question doesn't actually do anything.
Alan Moore
Just an example.
dr.manhattan
A: 

Maybe this would work:

Remove the double backslashes from the parameter of the split method:

split = docStr.split("\n");
Michael Angstadt
bad idea - you need the backslash for escaping...
Yuval A
Not really. When you write a regex in the form of a Java String literal, you can use "\n" to pass the regex compiler a linefeed symbol, or "\\n" to pass it the escape sequence for a linefeed. The same goes for all the other whitespace escapes except \v, which isn't supported in Java literals.
Alan Moore
A: 

i have more confusion in designing of control flow graph in java if any one knows the code to generate cfg plz send it to my mail and my mail id is [email protected]

mahesh