java - How to get a Scanner to ignore words between a certain pattern -
i want read input file using scanner, want scanner ignore inside (* ....... *). how do this? i'm taking integers , adding them array list, if there integers inside text want ignore adds too.
public arraylist<integer> readnumbers(scanner sc) { // todo implement readnumbers arraylist<integer> list = new arraylist<integer>(); while(sc.hasnext()) { try { string temp = sc.next(); list.add(integer.parseint(temp)); } catch(exception e) { } } return list; } here's example line of text file
(* 21 alabama population in 2013 *) 4802740
i add 21 , 4802740 array list. thought using sc.usedelimiter("("); sc.usedelimiter(")"); can't seem work. thanks!
it seems may looking
sc.usedelimiter("\\(\\*[^*]*\\*\\)|\\s+"); this regular expression \\(\\*[^*]*\\*\\) represents part
\\(\\*- starts(*,\\*\\)- ends*)[^*]*- , have 0 or more non*characters inside.
i added |\\s+ allow 1 or more spaces delimiter (this delimiter used scanners default).
btw using try-catch main part of control flow considered wrong. instead should change code like
while (sc.hasnext()) { if(sc.hasnextint()) { list.add(sc.nextint()); } else { //consume data not interested in //so scanner move on next tokens sc.next(); } }
Comments
Post a Comment