gpt4 book ai didi

java - 在 Java 中获取括号内的参数并将其添加到列表中

转载 作者:行者123 更新时间:2023-12-02 02:53:13 26 4
gpt4 key购买 nike

输入:

(cl(A, B, 0.620) :-  /* #pos=1,513 *

预期输出:

Fetch and Add A and B to a list

代码(尝试 1):

Matcher m2 = Pattern.compile("\\((.*?)\\)").matcher(inputString);
while(m2.find())
{
System.out.println(m2.group(1));
}

输出:

cl(A, B, 0.620

代码尝试2:

System.out.println(inputString.substring(inputString.indexOf("(")+1,inputString.indexOf(")")));

仍然得到相同的输出。

请告诉我错误所在。

最佳答案

您当前尝试的主要问题是您的模式错误:

\\((.*?)\\)

它匹配一个单个左括号,后跟一个单个右括号。请注意,模式中的捕获组不算在内;这些括号不会匹配。相反,请使用以下模式:

\\(.*?\\((.*?)\\)

完整代码:

String inputString = "(cl(A, B, 0.620) :-  /* #pos=1,513 *";
List<String> list = new ArrayList<>();
Matcher m2 = Pattern.compile("\\(.*?\\((.*?)\\)").matcher(inputString);
if (m2.find()) {
String match = m2.group(1);
String[] parts = match.split(",\\s+");
for (String part : parts) {
list.add(part);
System.out.println("Found an item: " + part);
}
}

输出:

Found an item: A
Found an item: B
Found an item: 0.620

此处演示:

Rextester

关于java - 在 Java 中获取括号内的参数并将其添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43501839/

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