I have incoming message in two slightly different formats like:
I can sucessfully extract string from the first format using below method:
String message = "Info : STD ID2.7384733928374. PSSID, SSN:324920349023742903, END";
String prefix1 = "ID";
String suffix1 = ".";
String output1 = message.substring(message.indexOf(prefix1) + prefix1.length(), message.indexOf(suffix1));
Log.d("Output1", output1);
String prefix2 = ".";
String suffix2 = ". PSSID";
String output2 = message.substring(message.indexOf(prefix2) + prefix2.length(), message.indexOf(suffix2));
Log.d("Output2", output2);
// Output2: 7384733928374 (correct)
But Cannot extract from the second format using the same method as above:
String message = "Info : STD Z10 1234567890123 PSSID, SSN:12394847382940398433, END";
String prefix1 = "Z";
String suffix1 = " ";
String output1 = message.substring(message.indexOf(prefix1) + prefix1.length(), message.indexOf(suffix1));
Log.d("Output1", output1);
String prefix2 = " ";
String suffix2 = " PSSID";
String output2 = message.substring(message.indexOf(prefix2) + prefix2.length(), message.indexOf(suffix2));
Log.d("Output2", output2);
Please help me how to extract the 10 and 1234567890123 from the second format?
You can use regex to match both situations:
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(message);
matcher.find();
System.out.println(matcher.group());
matcher.find(matcher.end());
System.out.println(matcher.group());