java.util.scanner - Java scanner won't match square brackets -
i having trouble parsing python lists scanners in java. reason seem doing wrong when attempting detect square brackets. puzzles me seems somehow occurences of square brackets in input triggers unwanted behaviour.
scanner scanner1 = new scanner("a["); assert(scanner1.hasnext("a\\[")); // not trigger assertion scanner scanner2 = new scanner("[[0]]"); assert(scanner2.hasnext("\\[")); // triggers assertion, why? scanner scanner3 = new scanner(" a[[[0]]"); assert(scanner3.hasnext("a\\[")); // triggers assertion, why?
this using
openjdk version "1.8.0_45" openjdk runtime environment (build 1.8.0_45-b14) openjdk 64-bit server vm (build 25.45-b02, mixed mode)
scanner
a scanner split input tokens, splitted delimiter (nice explanation http://www.tutorialspoint.com/java/util/java_util_scanner.htm), default whitespace. since don't have delimiting characters, first token whole string, pattern in hasnext
should match whole string , not parts of it.
solution: need create correct regexp syntax match whole string
scanner scanner1 = new scanner("a["); assert(scanner1.hasnext("a\\[")); scanner scanner2 = new scanner("[[0]]"); assert(scanner2.hasnext("\\[.*")); scanner scanner3 = new scanner(" a[[[0]]"); assert(scanner3.hasnext("a\\[.*"));
another method use findinline
scanner scanner2 = new scanner("[[0]]"); string inline = scanner2.findinline("\\[.*")); assert(inline!=null);
Comments
Post a Comment