-1

I have a string like this:

String = IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 DATE RIGHTS

I want to only match and print out115956 | 40.104730 | -88.228798. How do I do it with regular expression?

Here is my code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Test3
{
   private static String REGEX = "\\d+\\.\\d";
   private static String INPUT = "IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 ";
   private static String REPLACE = "-";

   public static void main(String[] args) {

      Pattern p = Pattern.compile(REGEX);
      Matcher m = p.matcher(INPUT);           // get a matcher object
      StringBuffer sb = new StringBuffer();
      while(m.find()){
         m.appendReplacement(sb,REPLACE);
      }
      m.appendTail(sb);
      System.out.println(sb.toString());
   }
}

But my results are like this: IDENTIFIER: 115956 LATITUDE: -04730 LONGITUDE: --28798.

qximin
  • 167
  • 1
  • 2
  • 11
  • Probably better duplicate: http://stackoverflow.com/questions/15894729/extract-number-from-string-using-regex-in-java – Pshemo Mar 18 '15 at 20:00
  • `m.appendReplacement(sb,REPLACE);` will place found match with value of `REPLACE`. I doubt that it is what you want. Consider using `StringJoiner` with delimiter `" | "` and place each number you found in your input to generate `115956 | 40.104730 | -88.228798`. – Pshemo Mar 18 '15 at 20:10

2 Answers2

1

You can use a regex like this:

IDENTIFIER:\s(\d*)\sLATITUDE:\s(\d*\.?\d*)\sLONGITUDE:\s(.*?)\s

Working demo

enter image description here

Match information

MATCH 1
1.  [12-18] `115956`
2.  [29-38] `40.104730`
3.  [50-60] `-88.228798`

You can test it like using this code:

   public static void main(String args[]) {
        String line = "IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 DATE RIGHTS"; 
        String pattern = "IDENTIFIER:\\s(\\d*)\\sLATITUDE:\\s(\\d*\\.?\\d*)\\sLONGITUDE:\\s(.*?)\\s";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);

        if (m.find()) {
            System.out.println("Found value: " + m.group(1));
            System.out.println("Found value: " + m.group(2));
            System.out.println("Found value: " + m.group(3));
        } else {
            System.out.println("NO MATCH");
        }
    }
Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
0

You can do a String replaceAll, capturing the groups you care about:

class Reg {
    static String s = "IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 DATE RIGHTS";

    static public void main(String[] args) {
        String r = s.replaceAll("IDENTIFIER: ([0-9]+) LATITUDE: ([-+]?(\\d*[.])?\\d+) LONGITUDE: ([-+]?(\\d*[.])?\\d+).*$", "$1 | $2 | $4");
        System.out.println(r);
    }
}

$ javac Reg.java
$ java Reg
115956 | 40.104730 | -88.228798
jas
  • 10,715
  • 2
  • 30
  • 41