Search code examples
androidsubstringprefixsuffix

Cannot extract a string from incoming message using prefix and suffix in android


I have incoming message in two slightly different formats like:

  1. "Info : STD ID2.7384733928374. PSSID, SSN:324920349023742903, END"
  2. "Info : STD Z10 1234567890123 PSSID, SSN:12394847382940398433, END"

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)
  1. Output1: 2 (correct) and
  2. 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);
  1. Output1: error java.lang.StringIndexOutOfBoundsException: length=65; regionStart=12; regionLength=-8
  2. Output2 STD Z10 1234567890123 (wrong) correct output should be 1234567890123

Please help me how to extract the 10 and 1234567890123 from the second format?


Solution

  • 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());