I'm extracting three parts of a string with regex in Java and the following working code. I'm relatively new in regex and I'm feeling a bit silly using several expressions for such a simple search and extraction.
Can anyone of you help me with a more elegant and simple solution? I need the data to be stored in three seperate variables as the code suggests.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String input = "lat: 56.894205 long: 008.528896 speed: 000.0 24/02/13 21:21 bat:F signal:F imei:12345678901";
String lat = regexSearch("(?<=lat: )\\d+.\\d+", input);
String lng = regexSearch("(?<=long: )\\d+.\\d+", input);
String imei = regexSearch("(?<=imei:)\\d+", input);
if (lat != null && lng != null && imei != null) {
System.out.println(lat);
System.out.println(lng);
System.out.println(imei);
}
}
public static String regexSearch(String regex, String input) {
Matcher m = Pattern.compile(regex).matcher(input);
if (m.find()) return m.group();
return null;
}
}
Output:
56.894205
008.528896
12345678901
Edit: I need the code to handle varying length of the "lat" and "long" data (e.g. 56.89405 and 56.894059 etc.)