gpt4 book ai didi

java - 正则表达式匹配返回 false

转载 作者:行者123 更新时间:2023-12-04 20:41:04 25 4
gpt4 key购买 nike

下面的代码执行正常,我能够获取所有值,但 matcher.matches() 返回 false。

final Matcher matcher = Pattern.compile("\\((-?\\d+),(-?\\d+)\\)").matcher("(8,0),(0,-1),(7,-2),(1,1)");

System.out.println("Matches: " + matcher.matches());
int index = 0;
while (matcher.find()) {
point[index] = new Point(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)));
index++;
}

谁能告诉我为什么 matcher.matches() 返回 false

最佳答案

尝试使用此正则表达式进行匹配:^\(-?\d+,-?\d+\)(,\s*\(-?\d+,-?\d+\)){3}$

Pattern pattern = Pattern.compile("^\\(-?\\d+,-?\\d+\\)(\\s*,\\(-?\\d+,-?\\d+\\)){3}$");

// this will match
Matcher matcher = pattern.matcher("(8,0),(0,-1),(7,-2),(1,1)");
System.out.println("Matches: " + matcher.matches());

// this will not match
matcher = pattern.matcher("(8,0),(0,-1),(7,-2),(1,1");
System.out.println("Matches: " + matcher.matches());

// neither will this one, which has a dangling comma
matcher = pattern.matcher("(8,0),(0,-1),(7,-2),");
System.out.println("Matches: " + matcher.matches());

// neither will this one, which has too few order pairs
matcher = pattern.matcher("(8,0),(0,-1),(7,-2)");
System.out.println("Matches: " + matcher.matches());

// neither will this one, which has too many order pairs
matcher = pattern.matcher("(8,0),(0,-1),(7,-2),(1,1),(3,-5)");
System.out.println("Matches: " + matcher.matches());

关于java - 正则表达式匹配返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32578896/

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