user481610
user481610

Reputation: 3270

Java split() not working as expected

I currently have text where I have "TweetJSONObject\r\n09/19/14TweetJSONObject" where the TweetJSONObject is just a tweet in json format. Now I'm using the .split() function to try separate the tweets from one another but it would seem that \r\n09/19/14 isn't an appropriate split string? Here is the code:

String[] value = line.split("\r\n09/19/14");

PrintWriter writer = new PrintWriter("hello.txt", "UTF-8");
writer.println(value[0]);
writer.close();

The text file 'hello', when I open it is just the following string again, "TweetJSONObject\r\n09/19/14TweetJSONObject". Any ideas as to where I'm going wrong?

Upvotes: 0

Views: 144

Answers (3)

Jean Logeart
Jean Logeart

Reputation: 53829

You need to escape the backslashes:

String[] value = line.split("\\\\r\\\\n09/19/14");

Why so many backslashes?

In literal Java strings the backslash is an escape character. The literal string "\\" is a single backslash. In regular expressions, the backslash is also an escape character. The regular expression \\ matches a single backslash. So this regular expression as a Java string, becomes "\\\\".

Upvotes: 3

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23208

I would recommend using the library method Pattern.quote instead of trying to escape stuff on your own (which is too confusing and error prone). A small runnable example:

package net.sanjayts;

import java.util.regex.Pattern;

public class RegexTest {
    public static void main(String[] args) {
        String s = "TweetJSONObject\r\n09/19/14TweetJSONObject";
        String[] parts = s.split(Pattern.quote("\r\n09/19/14"));
        System.out.println(parts[0] + " --- " + parts[1]);
    }
}

//Output: TweetJSONObject --- TweetJSONObject

Upvotes: 1

Michael
Michael

Reputation: 719

You need to escape the slashes

String[] value = line.split("\\\\r\\\\n09/19/14");

PrintWriter writer = new PrintWriter("hello.txt", "UTF-8");
writer.println(value[0]);
writer.close();

Upvotes: 0

Related Questions