Java的正则表达式在文件中匹配十六进制数字
问题描述:
所以我读的文件(如Java程序< TRACE.DAT),它看起来是这样的:Java的正则表达式在文件中匹配十六进制数字
58
68
58
68
40
c
40
48
FA
如果我是幸运的,但更多的时候它在每行之前和之后都有几个空白字符。
这些是我正在解析的十六进制地址,我基本上需要确保我可以使用扫描器,缓冲读取器......以及确保我可以将十六进制转换为整数。这是我到目前为止有:
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...
所以我跟踪我所有的错误,分析输入的东西,所以我想我只是想弄清楚我需要得到这个工作什么的正则表达式或方法我想要的方式。
答
s.next()
照顾白色空间。 (默认标志不关心他们。)
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));
}
}
如果你真的想坚持使用模式的方法,我会建议你使用XDigit类:
\p{XDigit} A hexadecimal digit: [0-9a-fA-F]
更多; scanner.next(pattern)
将返回整个匹配模式(包括空白!)您需要使用捕获组。尝试模式
^\\s*(\\p{XDigit}+)\\s*$
这里得到实际的十六进制数是我所得到的,当我尝试这样的:在线程“主要” java.lang.NumberFormatException 例外:对于输入字符串: “” \t在java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) \t在java.lang.Integer.parseInt(Integer.java:470) \t在Cache.access(Cache.java:82) \t at Cache.main(Cache.java:136) – ranman 2010-05-03 08:04:35
当你尝试我建议的代码? – aioobe 2010-05-03 08:07:47
我正在尝试修复一个错误,对不起,我在代码中的其他地方不断收到InputMismatchException。 – ranman 2010-05-03 08:16:07