java.util.scanner - Java scanner searches same pattern twice -
i expect following code find tokens of pattern available. parse shell command iwlist wlp3s0 scanning
, there more 1 access point (repeating pattern). need parse them somehow.
scanner s = new scanner(commandoutput); string pattern = ".*?address: (\\s*) .*?channel:(\\d*) .*?frequency:(\\s*) .*?quality=(\\d*)/(\\d*) .*?signal level=-(\\d*)"; //s.findinline(pattern); while(true){ s.findinline(pattern); matchresult result = s.match(); (int = 1; <= result.groupcount(); i++) { system.out.println(result.group(i)); } }
but throws exception: java.lang.illegalstateexception
.
how check if has more matches while iterating through loop instead of while(true)
, exception?
the issue match()
method:
public matchresult match()
returns match result of last scanning operation performed scanner. method throws illegalstateexception if no match has been performed, or if last match not successful.
but why problem? there match performed, can not successful. let's @ doc findinline
(the actual info variant accepting pattern argument):
public string findinline(pattern pattern)
attempts find next occurrence of specified pattern ignoring delimiters. if pattern found before next line separator, scanner advances past input matched , returns string matched pattern. if no such pattern detected in input next line separator, null returned , scanner's position unchanged. method may block waiting input matches pattern.
since method continues search through input looking specified pattern, may buffer of input searching desired token if no line separators present.
so soes do? matches pattern, , puts "marker" @ end of string matched. not contain actual line, next findinline
call try match left (line break chars, etc) - , not able so...
the scanner has consume until end of line able go ahead issuing nextline()
call, , not using returned string:
scanner s = new scanner(commandoutput); string pattern = ".*?address: (\\s*) .*?channel:(\\d*) .*?frequency:(\\s*) .*?quality=(\\d*)/(\\d*) .*?signal level=-(\\d*)"; //instead of "true, use hasnextline()" while(s.hasnextline()){ s.findinline(pattern); matchresult result = s.match(); (int = 1; <= result.groupcount(); i++) { system.out.println(result.group(i)); } s.nextline(); // consume line }
Comments
Post a Comment