我收到的消息有两种略有不同的格式,如:
我可以使用以下方法从第一种格式中成功提取字符串:
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)
但无法使用与上述相同的方法从第二种格式中提取
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);
请帮我解决如何从第二种格式中提取10和1234567890123的问题?
答案 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());