Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

split string using regex in java

807603Feb 14 2008 — edited Feb 14 2008
Hello,
I've a flat file of data exported from a DB table. Columns are delimited with "|" (pipe) character. For e.g: there are 9 columns of data type varchar as:

ID|TYPE|NAME|ADDRESS|ZIP|STATE|TEL|FAX|PREFIX

and some of which can have null value in the table. Now, I'm trying to read the flat file line by line and read out the column values using :

Pattern p = Pattern.compile("[|]+");
String[] result = p.split(str);

where variable str holds a record line. My problem is that, since some of the columns are null , I get only those elements which are not null in the result[] array.By looping through result[] array, I'll not be able to tell which columns were null. For e.g:
Splitting record line "1003|2|Family Preserve||15809|VA|||"
will put 5 elements into result[] array.I have no means to say which 4 columns were not present in the record. Is there any way to have a result array that would contain all the 9 column data, with some of the being null.


here is the simplified code , that I'm trying to figure out:
import java.util.regex.Pattern;
public class ReadSplit {

	public static void main(String [] args) {
		
		//columns: ID|TYPE|NAME|ADDRESS|ZIP|STATE|TEL|FAX|PREFIX
		String str= "1003|2|Family Preserve||15809|VA|||";
		
		Pattern p = Pattern.compile("[|]+");
		String[] result = p.split(str);
		
		// this is printing out only 5, I want to
		// see all 9 entries, with some of them being null
		// wherever column data is null, so I can know which column was null
		System.out.println("result.length:"+result.length);
	}
}
I'm thinking of simpler approach of using regex, any other efficient way to achieve same is welcome. Thanks for any responses...
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 13 2008
Added on Feb 14 2008
2 comments
245 views