Java Language Scanner Using custom delimiters

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Example

You can use custom delimiters (regular expressions) with Scanner, with .useDelimiter(","), to determine how the input is read. This works similarly to String.split(...). For example, you can use Scanner to read from a list of comma separated values in a String:

Scanner scanner = null;
try{
    scanner = new Scanner("i,like,unicorns").useDelimiter(",");;
    while(scanner.hasNext()){
        System.out.println(scanner.next());
    }
}catch(Exception e){
    e.printStackTrace();
}finally{
    if (scanner != null)
        scanner.close();
}

This will allow you to read every element in the input individually. Note that you should not use this to parse CSV data, instead, use a proper CSV parser library, see CSV parser for Java for other possibilities.



Got any Java Language Question?