You can use String[] split(String regex, int limit) as follows:
String[] tests = { "NAME*ADRESS LINE1*ADDRESS LINE2*", "NAME*ADRESS LINE1**", "NAME**ADDRESS LINE2*", "NAME***", "*ADDRESS LINE1*ADDRESS LINE2*", "*ADDRESS LINE1**", "**ADDRESS LINE2*", "***", "-MS DEBBIE GREEN*1036 PINEWOOD CRES**", }; for (String test : tests) { test = test.substring(0, test.length() - 1); String[] parts = test.split("\\*", 3); System.out.printf( "%s%n Name: %s%n Address Line1: %s%n Address Line2: %s%n%n", test, parts[0], parts[1], parts[2] ); }
This prints ( as seen on ideone.com ):
NAME*ADRESS LINE1*ADDRESS LINE2* Name: NAME Address Line1: ADRESS LINE1 Address Line2: ADDRESS LINE2 NAME*ADRESS LINE1** Name: NAME Address Line1: ADRESS LINE1 Address Line2: NAME**ADDRESS LINE2* Name: NAME Address Line1: Address Line2: ADDRESS LINE2 NAME*** Name: NAME Address Line1: Address Line2: *ADDRESS LINE1*ADDRESS LINE2* Name: Address Line1: ADDRESS LINE1 Address Line2: ADDRESS LINE2 *ADDRESS LINE1** Name: Address Line1: ADDRESS LINE1 Address Line2: **ADDRESS LINE2* Name: Address Line1: Address Line2: ADDRESS LINE2 *** Name: Address Line1: Address Line2: -MS DEBBIE GREEN*1036 PINEWOOD CRES** Name: -MS DEBBIE GREEN Address Line1: 1036 PINEWOOD CRES Address Line2:
The reason for "\\*" is that split accepts a regular expression, and * is a metacharacter for regular expressions, and since you want it to mean literally, it needs to be escaped with \ . Since \ itself is the escape character of a Java string, to get \ in a string, you need to double it.
The reason for limit in 3 is because you want the array to have 3 parts, including the completion of empty lines. A limit -less split by default discards empty lines.
The last * discarded manually before split executed.
source share