How to parse a quoted string with java.util.Scanner

The Java 5.0 version of java.util.Scanner does not support quoted string tokens.
The class ScannerEx below adds support for scanning quoted strings to java.util.Scanner.

(Unfortunately java.util.Scanner cannot be subclassed, because it's "final". See my feature request (please vote for it))

Download (Java source files): ScannerEx.zip



// Extension routines for java.util.Scanner, to support scanning of quoted strings.
// Author: Christian d'Heureuse (http://www.source-code.biz)
public class ScannerEx {

private java.util.Scanner    sc;

// Constructor, used to pass the java.util.Scanner object.
// Note: We cannot subclass java.util.Scanner, because unfortunately
// it's declared as "final".
public ScannerEx (java.util.Scanner sc) {
   this.sc = sc; }

// Returns true if the next token is the beginning of a quoted string value.
public boolean hasNextQuotedString() {
   return sc.hasNext("\\\".*"); }

// Scans a quoted string value from the scanner input.
public String nextQuotedString() {
   if (!sc.hasNext()) throw new java.util.NoSuchElementException();
   if (!hasNextQuotedString()) throw new java.util.InputMismatchException();
      // This is necessary because findInLine would skip over other tokens.
   String s = sc.findInLine("\\\".*?\\\"");
   if (s == null) throw new java.util.InputMismatchException();
   return s.substring(1,s.length()-1); }

} // end of class ScannerEx



// Test for ScannerEx.nextQuotedString().
private static void testScannerEx() {
   final String s = "123 \" abc def \" \"xyz\" 456";
   Scanner sc = new Scanner(s);
   ScannerEx sce = new ScannerEx(sc);
   if (sc.nextInt() != 123)
      throw new Error();
   if (!sce.nextQuotedString().equals(" abc def "))
      throw new Error();
   if (!sce.nextQuotedString().equals("xyz"))
      throw new Error();
   if (sc.nextInt() != 456)
      throw new Error(); }


Author: Christian d'Heureuse (www.source-code.biz, www.inventec.ch/chdh)
License: Free / LGPL
Index