0

My regular expression has 2 different outputs from the same code... but i don't know what's wrong. Here's a piece of code, i hope you can help me. Thanks!

String s = "48° 18′ 13,94″ nördliche Breite, "
         + "11° 34′ 31,98″ östliche Länge";

String kommazahl = "[0-9]{1,2}([\\.,][0-9]+)?";
String zahl = "[0-9]{1,2}";

Pattern p1 = Pattern.compile("("+ zahl +"[°/| ]{1,2}"+ zahl +"(['′/| ]{1,2}("+ kommazahl +")?)?).*"
                            +"("+ zahl +"[°/| ]{1,2}"+ zahl +"(['′/| ]{1,2}("+ kommazahl +")?)?).*");

Matcher m1 = p1.matcher(s);

System.out.println(m1.group(1) + "\n" + m1.group(5));

// Output should be:
// 48° 18′ 13,94
// 11° 34′ 31,98

// Output is:
// 48° 18′ 13,94
// 1° 34′ 31,98
3
  • 8
    Why do so many people assume its a bug in the language rather than checking their own code more closely? Commented Jun 5, 2009 at 13:19
  • zahl seems to be wrong - degrees can have 3 digits. That has nothing to do with your problem, it may just be a bug. Commented Jun 5, 2009 at 13:56
  • 3
    Please pay attention to the suggest prompts when tagging your question. Any tag with a number less than 10 after it's name is probably wrong. Commented Jun 5, 2009 at 14:30

2 Answers 2

5

The .* matches the first 1 of 11 greedily, while still allowing the rest of the pattern to match. Replace .* with something like [^0-9]*.

Sign up to request clarification or add additional context in comments.

Comments

4

The problem is the .* at the end of the first line of the pattern. That's greedily matching "nördliche Breite, 1".

Perhaps you should change it to capture ".*, " so that it knows when to stop?

Pattern p1 = Pattern.compile
    ("("+ zahl +"[°/| ]{1,2}"+ zahl +"(['′/| ]{1,2}("+ kommazahl +")?)?).*, "
    +"("+ zahl +"[°/| ]{1,2}"+ zahl +"(['′/| ]{1,2}("+ kommazahl +")?)?).*");

Of course, that will only work if there's always a "comma space" between the two values you want in the rest of your data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.