Java Regex: Extracting info from string to variables -
I am removing the three parts of a string with regex in Java and the following working code is relatively new to regedx and I feel a bit stupid in using such expressions for simple exploration and extraction.
Can any of you help me with a more elegant and simple solution? I need to store the data in three different variables because the code suggests.
import java.util.regex.Matcher; Import java.util.regex.Pattern; Public category test {public static zero main (string [] args) {string input = "latitude: 56.894205 tall: 008.528896 speed: 000.0 24/02/13 21:21 bat: f signal: f imei: 12345678901"; String lat = regex search ("(? & Lt; = lat :) \\ d +. \\ d +", input); String lng = regex search ("(? & Lt; = tall :) \\ d +. \\ d +", input); String imei = regex search ("(? & Lt; = IMEI :) \\ d +", input); If (lat! = Null & lng! = Null & amp; imei! = Null) {System.out.println (lat); Println (LNG); Println (IMEI); }} Public static string regexSearch (string regex, string input) {Matcher m = Pattern.compile (regex) .matcher (input); If (m.find ()) return m.group (); Return tap; }} Output:
56.894205 008.528896 12345678901 Edit: Let me handle different lengths Code for "Latitude" and "Long" data (like 56.8 9 405 and 56.8 9 4059 etc.)
You can use different match groups and then specify each match group in the string variable of your choice. Below is an example of a work that you can stop ...
string: s = "lat: 56.894205 tall: 008.528896 speed: 000.0 24/02/13 21:21 bat: F signal : F imei: 12345678901 "; Pattern p = Pattern.compile ("lat: (? & Lt; lat & gt; \\ d + \\. \\ d +) long: (? & Lt; lng & gt; \\ d + \\. \ D +). * Imei: (? & Lt; IMEI & gt; \\ d +) "); Mitcher M = P. MATTER (S); While (m.find ()) {string lat = m.group ("lat"); String LNG = M. G. P. ("LNG"); String imei = m.group ("imei"); Println (lat); // = & gt; "56.894205" system. Outprint LN (LNG); // = & gt; "008.528896" system.out.printLN (imei); // = & gt; "12345678901"}
Comments
Post a Comment