【发布时间】:2015-03-13 06:45:40
【问题描述】:
我需要解析一个包含格式为该示例的整数的文件(用于对 DPLL 算法进行基准测试):
-486 535 0
-563 745 0
125 -430 512 -4 512 -4 0
512 -4 0
667 -19 0
40 -281 512 -4 0
-231 637 0
一般来说,数据的格式是这样的
number number number 0
numbers are separated by space and each line ends with the character 0,
例如 这可能是我要解析的字符串
545 -565 7 55 0
我想捕获这些数字中的每一个。
- 545 将是第一个
- -565 秒
- 7第三
- 55第四
而 0 用于分隔这些数字
谁能给我使用java的正则表达式来做到这一点?
我使用的代码是:
Pattern pattern = Pattern.compile("(\\-?\\d*)\\s*(\\-?\\d*)\\s*(\\-?\\d*)\\s*0");
Matcher matcher = pattern.matcher(sCurrentLine);
//System.out.print("hou find one");
if (matcher.find()) {
int id;
boolean val;
int i=1;
Clause tempClause = new Clause(counter);
do
{
id = Integer.parseInt(matcher.group(i));
val = id>0;
if (val == false)id*=-1;
tempClause.addLiteral(new Literal (id,val));
System.out.print("id "+id+" the current i:"+i+".\n");
i++;
}
while (i<3);
this.clauses.add(tempClause);
counter++;
System.out.print("the i:"+i+"\n");
}
使用这段代码我捕获了 3 个整数,我需要改进以捕获该字符串中的所有整数。
【问题讨论】:
-
是否需要使用正则表达式?
-
正则表达式就像
-?\d+一样简单。 -
我将编辑帖子以向您展示我正在使用的代码
-
使用两个步骤。一个正则表达式来获取整数行
(?s)\s*(.+?)\s+0\b然后在空格上拆分\s+ -
你能用
Scanner吗?我认为hasNextInt()和nextInt()非常适合这个。