Waylander
Waylander

Reputation: 825

Extract numbers from String in Java

Referring to this question here. I have a new Problem. I want to extract the last two appearing numbers (longitude/latitude) from a String.

I use the approach from the referenced answer. A simple example where the error occures can be found here:

public static void main(String[] args) {
    String input = "St. Louis (38.6389, -90.342)"; 

    Pattern p = Pattern.compile("-?[\\d\\.]+");
    Matcher m = p.matcher(input);

    while(m.find()){
        System.out.println(m.group());
    }
}

Console output is as following:

.
38.6389
-90.342

The Problem appears to be the "." in "St. Louis". Can someone help me to solve this issue in a nice way?

Thanks a lot for every answer/comment.

Upvotes: 0

Views: 79

Answers (3)

asontu
asontu

Reputation: 4659

A regex like -?\d*(?:\.\d+)? causes the engine to find zero-width matches everywhere. A better approach is to simply use alternation to require that either there is a dot with numbers or one or more numbers after which a dot with more numbers is optional:

-?(?:\.\d+|\d+(?:\.\d+)?)

Regular expression visualization

Debuggex Demo

In Java you need to escape this like so:

Pattern p = Pattern.compile("-?(?:\\.\\d+|\\d+(?:\\.\\d+)?)");

Alternatively, you could add a lookahead that requires that there is at least one number somewhere:

-?(?=\.?\d)\d*(?:\.\d+)?

Regular expression visualization

Debuggex Demo

Upvotes: 0

vks
vks

Reputation: 67988

[-+]?\\d+(\\.\\d+)?

Use this for floating numbers and integers.

The Problem appears to be the "." in "St. Louis"

Thats because of -?[\\d\\.]+ [] the character class.It can match any character defined inside class.

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174874

Change your regex like below,

Pattern p = Pattern.compile("-?\\d+(?:\\.\\d+)?");

(?:\\.\\d+)? at the last would make the decimal part as optional.

Upvotes: 3

Related Questions