gpt4 book ai didi

java - 编写正则表达式以捕获有符号整数

转载 作者:行者123 更新时间:2023-11-30 06:16:03 24 4
gpt4 key购买 nike

我需要解析一个包含格式为本示例的整数的文件(用于基准 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 个整数,我需要改进以捕获该字符串中的所有整数。

最佳答案

您可以使用 Scanner 执行此操作:

public static void main(String[] arguments) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("data.txt"));
List<Integer> integers = new ArrayList<Integer>();
while (scanner.hasNext()) {
int i = scanner.nextInt();
if (i != 0)
integers.add(i);
}
System.out.println(integers);
}

数据.txt

-486 535 0
-563 745 0
125 -430 512 -4 512 -40
512 -4 0
667 -19 0
40 -281 512 -4 0
-231 637 0

输出

[-486, 535, -563, 745, 125, -430, 512, -4, 512, -40, 512, -4, 667, -19, 40, -281, 512, -4, -231, 637]

关于java - 编写正则表达式以捕获有符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27953869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com