So I’m reading in a file (like java program < trace.dat) which looks something like this:
58
68
58
68
40
c
40
48
FA
If I’m lucky but more often it has several whitespace characters before and after each line.
These are hexadecimal addresses that I’m parsing and I basically need to make sure that I can get the line using a scanner, buffered reader… whatever and make sure I can then convert the hexadecimal to an integer. This is what I have so far:
Scanner scanner = new Scanner(System.in);
int address;
String binary;
Pattern pattern = Pattern.compile("^\\s*[0-9A-Fa-f]*\\s*$", Pattern.CASE_INSENSITIVE);
while(scanner.hasNextLine()) {
address = Integer.parseInt(scanner.next(pattern), 16);
binary = Integer.toBinaryString(address);
//Do lots of other stuff here
}
//DO MORE STUFF HERE...
So I’ve traced all my errors to parsing input and stuff so I guess I’m just trying to figure out what regex or approach I need to get this working the way I want.
The
s.next()takes care of the white-spaces. (The default tokenizer doesn’t care about them.)If you’d really like to stick with the Pattern-approach, I would recommend you to use the XDigit class:
Further more; The
scanner.next(pattern)will return the entire matched pattern (including the white-spaces!) You need to work with capturing groups. Try the patternAnd then get the actual hex-number with matcher.group(1)