sc = new Scanner(new File(dataFile)); sc.useDelimiter(",|\r\n");
I don't understand how delimiter works, can someone explain this in layman terms?
The scanner can also use delimiters other than whitespace. Easy example from Scanner API: String input = "1 fish 2 fish red fish blue fish"; // \\s* means 0 or more repetitions of any whitespace character // fish is the pattern to find Scanner s = new Scanner(input). useDelimiter("\\s*fish\\s*"); System.
The delimiter() is a method of Java Scanner class which is used to get the Pattern which the Scanner class is currently using to match delimiters.
useDelimiter(String pattern) method Sets this scanner's delimiting pattern to a pattern constructed from the specified String.
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish"; // \\s* means 0 or more repetitions of any whitespace character // fish is the pattern to find Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); // prints: 1 System.out.println(s.nextInt()); // prints: 2 System.out.println(s.next()); // prints: red System.out.println(s.next()); // prints: blue // don't forget to close the scanner!! s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters 123… Digits \d Any Digit \D Any Non-digit character . Any Character \. Period [abc] Only a, b, or c [^abc] Not a, b, nor c [a-z] Characters a to z [0-9] Numbers 0 to 9 \w Any Alphanumeric character \W Any Non-alphanumeric character {m} m Repetitions {m,n} m to n Repetitions * Zero or more repetitions + One or more repetitions ? Optional character \s Any Whitespace \S Any Non-whitespace character ^…$ Starts and ends (…) Capture Group (a(bc)) Capture Sub-group (.*) Capture all (ab|cd) Matches ab or cd
With Scanner the default delimiters are the whitespace characters.
But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:
So useDelimiter()
methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:
And here is an Example:
public static void main(String[] args) { // Initialize Scanner object Scanner scan = new Scanner("Anna Mills/Female/18"); // initialize the string delimiter scan.useDelimiter("/"); // Printing the tokenized Strings while(scan.hasNext()){ System.out.println(scan.next()); } // closing the scanner stream scan.close(); }
Prints this output:
Anna Mills Female 18
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With