正则表达式匹配返回false

时间:2015-09-15 06:13:08

标签: java regex

以下代码执行正常,我可以获取所有值,但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

5 个答案:

答案 0 :(得分:2)

仅当整个String与整个正则表达式匹配时,

matches才返回true。

对于您的情况,只有部分字符串与正则表达式匹配

即。 (8,0)匹配正则表达式,但不匹配整个字符串

答案 1 :(得分:2)

尝试使用此正则表达式进行匹配:^\(-?\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());

答案 2 :(得分:1)

matches要求整个字符串匹配,因此您需要重复您的模式:

"(\\((-?\\d+),(-?\\d+)\\), )*\\((-?\\d+),(-?\\d+)\\)"

这是:

(pattern, )*pattern

因此它将匹配一个或多个坐标,以逗号空格分隔。

答案 3 :(得分:1)

据我所知,在重复组中不可能使用匹配组。只匹配第一个和最后一个组。 但你可以先检查字符串是否与正则表达式匹配而不捕获组,然后自行拆分字符串。

final String coords = "(8,0),(0,-1),(7,-2),(1,1)";

if (coords.matches("\\(-?\\d+,-?\\d+\\)(?:, ?\\(-?\\d+,-?\\d+\\))*")) {
    final String[] splitted = coords.replaceAll(" |\\(|\\)", "").split(",");
    final Point[] points = new Point[splitted.length / 2];

    for (int i = 0; i < splitted.length; i += 2) {
        points[i / 2] = new Point(Integer.parseInt(splitted[i]), Integer.parseInt(splitted[i + 1]));
    }
}

由于您不知道字符串中给出了多少坐标,因此您应使用List来存储提取的Point

final String coords = "(8,0),(0,-1),(7,-2),(1,1)";
final List<Point> points = new ArrayList<>();

if (coords.matches("\\(-?\\d+,-?\\d+\\)(?:, ?\\(-?\\d+,-?\\d+\\))*")) {
    final String[] splitted = coords.replaceAll(" |\\(|\\)", "").split(",");

    for (int i = 0; i < splitted.length; i += 2) {
        points.add(new Point(Integer.parseInt(splitted[i]), Integer.parseInt(splitted[i + 1])));
    }
}

答案 4 :(得分:0)

只需使用以下正则表达式:

((^|,)\(-?\d+,-?\d+\))+$

以下是一个例子:

String str = "(8,0),(0,-1),(7,-2),(1,1)";
Pattern pattern = Pattern.compile("((^|,)\\(-?\\d+,-?\\d+\\))+$");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.matches());

输出:

true

或者你可以使用:

str.matches("((^|,)\\(-?\\d+,-?\\d+\\))+$");