Java Regex用于匹配文件中的十六进制数字 [英] Java Regex for matching hexadecimal numbers in a file
问题描述
所以我正在阅读一个文件(如java程序< trace.dat),它看起来像这样:
58
68
58
68
40
c
40
48
FA
如果我很幸运,但更经常的是每行前后有几个空白字符。
这些是我正在解析的十六进制地址,我基本上需要确保我可以使用扫描器,缓冲读取器......来获取行,并确保可以将十六进制转换为整数。这是我迄今为止:
扫描仪扫描仪=新的扫描仪(System.in);
int地址;
字符串二进制;
Pattern pattern = Pattern.compile(^ \\ * * [0-9A-Fa-f] * \\s * $,Pattern.CASE_INSENSITIVE);
while(scanner.hasNextLine()){
address = Integer.parseInt(scanner.next(pattern),16);
binary = Integer.toBinaryString(address);
//在这里做很多其他的东西
//在这里做更多的东西...
所以我把所有的错误都追溯到解析输入和东西,所以我想我只是想弄清楚我需要什么样的正则表达式或方法来实现这种工作方式。 p>
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));
$ b如果你真的想坚持模式-approach,我建议你使用XDigit类:
\ p {XDigit}十六进制数字:[0- 9a-fA-F]
更多; scanner.next(pattern)
将返回整个匹配模式(包括空格!)您需要使用捕获组。尝试模式
^ \\s *(\\p {XDigit} +)\\s *
然后用 matcher.group(1) p>
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.)
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'd really like to stick with the Pattern-approach, I would recommend you to use the XDigit class:
\p{XDigit} A hexadecimal digit: [0-9a-fA-F]
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 pattern
^\\s*(\\p{XDigit}+)\\s*$
And then get the actual hex-number with matcher.group(1)
这篇关于Java Regex用于匹配文件中的十六进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!