Java Reference
In-Depth Information
break
break ;
}
} else
else iif ( s . charAt ( j ) == '"' && j + 1 == len ) { // end quote @ line end
break
break ; //done
}
sb . append ( s . charAt ( j ));
// regular character.
}
return
return j ;
}
/** advPlain: unquoted field; return index of next separator */
protected
protected int
int advPlain ( String s , StringBuffer sb , int
int i )
{
int
int j ;
j = s . indexOf ( fieldSep , i ); // look for separator
Debug . println ( "csv" , "i = " + i + ", j = " + j );
iif ( j == - 1 ) {
// none found
sb . append ( s . substring ( i ));
return
return s . length ();
} else
else {
sb . append ( s . substring ( i , j ));
return
return j ;
}
}
}
In the online source directory, you'll find CSVFile.java , which reads a text file and runs it
through parse() . You'll also find Kernighan and Pike's original C++ program.
We haven't discussed regular expressions yet (we will in Chapter 4 ) . However, many readers
are familiar with regexes in a general way, so the following example demonstrates the power
of regexes, as well as providing code for you to reuse. Note that the following program re-
places all the code in both CSV.java and CSVFile.java (the key to understanding regexes is
that a little specification can match a lot of data): [ 15 ]
// package com.darwinsys.csv;
public
public class
implements CSVParser {
/** The rather involved pattern used to match CSV's consists of three
* alternations: the first matches a quoted field, the second unquoted,
* the third a null field.
*/
public
class CSVRE
CSVRE implements
public static
final String CSV_PATTERN =
"\"([^\"]+?)\",?|([^,]+),?|," ;
static final
 
Search WWH ::




Custom Search