无法使用android

时间:2017-08-25 06:55:52

标签: android substring prefix suffix

我收到的消息有两种略有不同的格式,如:

  1. "信息:STD ID2.7384733928374。 PSSID,SSN:324920349023742903,结束"
  2. "信息:STD Z10 1234567890123 PSSID,SSN:12394847382940398433,END"
  3. 我可以使用以下方法从第一种格式中成功提取字符串:

    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. 输出1:2(正确)和
    2. 输出2:7384733928374(正确)
    3. 但无法使用与上述相同的方法从第二种格式中提取

      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. 输出2 STD Z10 1234567890123 (错误)正确输出应为1234567890123
      3. 请帮我解决如何从第二种格式中提取10和1234567890123的问题?

2 个答案:

答案 0 :(得分:1)

这是解决方案,这肯定会带来您的预期答案。我已经在不同的工具中做了这个问题,对于不同的方法语法很抱歉,但希望答案是正确的。

    String message = "Info : STD Z10 1234567890123 PSSID, SSN:12394847382940398433, END";

        String prefix1 = "Z";
        String suffix1 = "0 ";
        String output1 = message.Substring(message.IndexOf(prefix1) + prefix1.Length, message.IndexOf(suffix1)-11);



        String prefix2 = "Z";
        String suffix2 = " PSSID";
        String output2 = message.Substring(message.IndexOf(prefix2) + prefix2.Length+2, message.IndexOf(suffix2)-14);

答案 1 :(得分:0)

您可以使用正则表达式来匹配这两种情况:

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