Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a String on | (pipe) in Java [duplicate]

I have the following text: ARIYALUR:ARIYALUR|CHENNAI:CHENNAI|COIMBATORE:COIMBATORE|CUDDALORE:CUDDALORE|DINDIGUL:DINDIGUL|ERODE:ERODE|KANCHEEPURAM:KANCHEEPURAM|KANYAKUMARI:KANYAKUMARI|KRISHNAGIRI:KRISHNAGIRI|MADURAI:MADURAI|NAMAKKAL:NAMAKKAL|NILGIRIS:NILGIRIS|PERAMBALUR:PERAMBALUR|PONDICHERRY:PONDICHERRY|SALEM:SALEM|THANJAVUR:THANJAVUR|THENI:THENI|THIRUVALLUR:THIRUVALLUR|THOOTHUKUDI:THOOTHUKUDI|TIRUNELVELI:TIRUNELVELI|VELLORE:VELLORE|VILLUPURAM:VILLUPURAM|VIRUDHUNAGAR:VIRUDHUNAGAR|

I tried to do a split("|") but my array is made up of single characters and not each district.

like image 590
user903772 Avatar asked Dec 26 '22 13:12

user903772


1 Answers

| is a special symbol in regular expression. Use \\| instead.

I'll explain why I appended 2 slashes. To escape the |, I need \|. However, to represent the string \|, "\\|" is required because \ itself needs to be escaped in a string lateral.

And, as xagyg has pointed out in the comment, split will treat the parameter as a regular expression. It will not be treated as a plain string.

In this use case, you may be interested to learn about Pattern.quote. You can do Pattern.quote("|"). This way, none of the characters will be treated as special ones.

like image 53
Haozhun Avatar answered Jan 09 '23 17:01

Haozhun