Java Regex to match hex numbers in a file

So, I am reading in a file (like java program <trace.dat) that looks something like this:

58
68
58
68
40
c
40
48
FA

      

If I'm lucky, but more often it has a few whitespace characters before and after each line.

These are the hex addresses that I am processing and basically I need to make sure I can get the string using a scanner, a buffered reader ... whatever I can convert the hex code 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 been tracking all my errors for parsing input, etc., so I guess I'm just trying to figure out what regex or approach I need to make it work the way I want it to.

+2


a source to share


1 answer


s.next()

takes care of white spaces. (The default denominator doesn't care about them.)

import java.util.Scanner;
public class Test {
    public static void main(String... args) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext())
            System.out.println(Integer.parseInt(s.next(), 16));
    }
}

      

If you really like to stick with the pattern, I would recommend you use the XDigit class:

\p{XDigit} A hexadecimal digit: [0-9a-fA-F]

      



Further; scanner.next(pattern)

will return the entire matched pattern (including spaces!). You need to work with capture groups. Try the pattern

^\\s*(\\p{XDigit}+)\\s*$

      

And then get the actual hexadecimal number with matcher.group (1)

+4


a source







All Articles