1

How do you assign an unknown substring (a Hex number) from a specific line in a txt file to a variable?

I've written the code to identify the necessary line and I've been told to use Regular Expressions (regex).

I don't know how to do that. Can it be done without regex?

This is an extract from an example txt file. I'm looking to get (and then compare Value(2) and Value(3)) but I need the Hex numbers first.

Default(2) = 0x00
Value(2) = 0xE0A64F36
Desc(2) = calculated from application
Address(2) = 0x60
Page(2) = Sensor
Name(3) = ROM CRC32
Type(3) = u32
Default(3) = 0x00
Value(3) = 0xE0A64F36
Desc(3) = fix CRC from ROM
4

4 回答 4

3

Split by = and parse the hexadecimal number.

String s = "Value(2) = 0xE0A64F36";
String hex = s.split("=")[1].trim();
long l = Long.parseLong(hex.substring(2), 16);
// l == 3768995638
于 2013-08-20T11:46:30.207 回答
1

You can do the extraction like this:

Pattern p = Pattern.compile("Value\\([23]\\) = (0x([0-9A-F]{8}))");
Matcher m = p.matcher(s);
while (m.find()) {
    System.out.println(m.group(1));
    System.out.println(Long.parseLong(m.group(2), 16));
}

Notice: if you want only to test if value(2) and value(3) are the same, you dont need to convert anything. You can only compare strings.

于 2013-08-20T11:46:24.283 回答
1

if you don't want to use regular expressions, you have to parse the string by the HEX pattern by yourself, such as getting the value part of the line (string after "=") and checking whether this part is in HEX format (starting with 0x and following characters are in 0-F) or using Integer.parseInt(String s, int radix) to try to parse it (catch the exception)

于 2013-08-20T11:46:36.160 回答
1

Assuming you have the strings already extracted and they are stored in 2 variables,

String value2 = "Value(2) = 0xE0A64F36";
String value3 = "Value(3) = 0xE0A64F36";

You can use substring and indexOf to get the actual value:

value2 = value2.substring(value2.indexOf("0x"));
value3 = value3.substring(value3.indexOf("0x"));
if (value2.compareToIgnoreCase(value3) == 0) {
  // Do something here
}
于 2013-08-20T11:48:56.277 回答