Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use the <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String,%20int%29" rel="nofollow noreferrer"><code>String[] split(String regex, int limit)</code></a> as follows:</p> <pre><code> 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] ); } </code></pre> <p>This prints (<a href="http://ideone.com/jETkj" rel="nofollow noreferrer">as seen on ideone.com</a>):</p> <pre><code>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: </code></pre> <p>The reason for the <code>"\\*"</code> is because <code>split</code> takes a regular expression, and <code>*</code> is a regex metacharacter, and since you want it to mean literally, it needs to be escaped with a <code>\</code>. Since <code>\</code> itself is a Java string escape character, to get a <code>\</code> in a string, you need to double it.</p> <p>The reason for the <code>limit</code> of <code>3</code> is because you want the array to have 3 parts, including trailing empty strings. A <code>limit</code>-less <code>split</code> discards trailing empty strings by default.</p> <p>The last <code>*</code> is discarded manually before the <code>split</code> is performed.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload