Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String split("|" ) method call not working correctly [duplicate]

Tags:

java

string

split

public class SplitStr {

    public static void main(String []args) {
        String str1 = "This | is | My | Account | For | Java|";
        String str2 = "This / is / My / Account / For / Java/";
       // String[] arr = str.split("|");

        for(String item : str1.split("|")) {
            System.out.print(item);
        }
    }
}

The program is working correctly with String str2 but it is not working with String str1 What are the possible flows in this program?

like image 716
user2677600 Avatar asked Jul 16 '14 08:07

user2677600


1 Answers

String#split() expects a regular expression as the first argument and | is a control character in regex.

To make regex parser understand that you mean to split by the literal |, you need to pass \| to the regex parser. But \ is a control character in Java string literals. So, to make Java compiler understand that you want to pass \| to the regex parser, you need to pass "\\|" to the String#split() method.

like image 126
Jae Heon Lee Avatar answered Sep 19 '22 15:09

Jae Heon Lee