user6845507
user6845507

Reputation:

Regex only matches once

I have the following regex that matches only once:

Matcher m = Pattern.compile("POLYGON\\s\\(\\((([0-9]*\\.[0-9]+)\\s([0-9]*\\.[0-9]+),?)+\\)\\)")
                   .matcher("POLYGON ((12.789754538957263 36.12443963532555,12.778550292768816 36.089875458584984,12.77760353347314 36.12427601168043))");
while (m.find()) {
    System.out.println("-> " + m.group(2) + " - " + m.group(3));
}

But it only prints the first match:

-> 12.789754538957263 - 36.12443963532555

Why does it not match the other coordinates?

I want to print a new line for each pair of coordinates, e.g.

12.789754538957263 - 36.12443963532555
12.778550292768816 - 36.089875458584984
12.77760353347314 - 36.12427601168043

Upvotes: 0

Views: 189

Answers (2)

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

You could still check if your input begins with a certain string like the following.

I'd use the following regex to do the check : (\[\\d.\]+)\\s(\[\\d.\]+)

It searches for sequences of digits or points separated by a space.

String input = ...
if (input.startsWith("POLYGON")) {
    Matcher m = Pattern.compile("([\\d.]+)\\s([\\d.]+)").matcher(input);
    while (m.find()) {
        System.out.println("-> " + m.group(1) + " - " + m.group(2));
    }
}

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59950

Your regex should look like this (\[0-9\]*\.\[0-9\]+)\s(\[0-9\]*\.\[0-9\]+)

String input = ...
Matcher m = Pattern.compile("([0-9]*\\.[0-9]+)\\s([0-9]*\\.[0-9]+)").matcher(input);
while (m.find()) {
    System.out.println("-> " + m.group(1) + " - " + m.group(2));
}

Outputs

-> 12.789754538957263 - 36.12443963532555
-> 12.778550292768816 - 36.089875458584984
-> 12.77760353347314 - 36.12427601168043

If you want to make sure that the input should between POLYGON (( .. )) you can use replaceAll to extract that inputs :

12.789754538957263 36.12443963532555,12.778550292768816 36.089875458584984,12.77760353347314 36.12427601168043

Your code should be :

.matcher(input.replaceAll("POLYGON \\(\\((.*?)\\)\\)", "$1"));

Instead of :

.matcher(input);

Solution 2

After analysing your problem, I think you need just this :

Stream.of(input.replaceAll("POLYGON \\(\\((.*?)\\)\\)", "$1").split(","))
             .forEach(System.out::println);

Upvotes: 1

Related Questions