× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to split a string in java with a specified delimiter while ignoring /?

Francis Galiegue
Apr 07, 2015
<p><a href="http://stackoverflow.com/a/29405183/1093528">@mushfek0001 got it right</a>.</p> <p>The pipe in most regex dialects is a metacharacter for the alternation; basically what you ask the regex engine to do here is: "split against the empty string or... the empty string".</p> <p>And, uh, it means you would potentially get empty each time, except that the regex engine is not a fool, and if an empty match is detected in a split the engine will advance one character before splitting again... Hence your result (not sure why the first element is <code>null</code> and not the empty string, though).</p> <p>Therefore, you should split against <code>"\\|"</code>, not <code>"|"</code>.</p> <p>What is more, if you do this repeatedly, use a <code>Pattern</code> instead:</p> <pre><code>private static final Pattern PIPE = Pattern.compile("\\|"); // ... final String[] tokens = PIPE.split(yourInput); </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29405164/How%20to%20split%20a%20string%20in%20java%20with%20a%20specified%20delimiter%20while%20ignoring%20/?/29405232">Stack Overflow</a>.</p>
comments powered by Disqus