Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse String with delimiter symbol into Array

I have a file containing lines of this type:

"Andorra la Vella|ad|Andorra la Vella|20430|42.51|1.51"

I basically just want to have a String Array containing the entries between the | delimiter:

["Andorra la Vella", "ad", "Andorra la Vella", "20430", "42.51", "1.51"]

Can this be done with regular expressions?

like image 924
gaussd Avatar asked Nov 02 '12 15:11

gaussd


People also ask

How do you parse a string with delimiters?

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.

How do I split a string into an array of strings?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I split a string with a specific symbol?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.


2 Answers

Yes use String.split() for each line as you read it from the file.

line.split("\\|");
like image 62
Aravind Yarram Avatar answered Sep 17 '22 21:09

Aravind Yarram


An alternative is to use String.split(...)

String s="Hi farshad zeinali/ how are you?/i have a question!/can you help me?";
String[] ss=s.split("/");
for(int i=0;i<ss.length;i++)
{
    System.out.println(ss[i]);
}
like image 45
user1794850 Avatar answered Sep 20 '22 21:09

user1794850