我正在开发一个Android应用程序,该应用程序汇总了从金融服务提供商发送给客户的短信,每次用户进行交易时,短信都会作为通知发送。 这是示例消息
[-ZAAD SHILLING-] Ref:1141125019 SLSH4,000发送给AXMED XASAN WARSAME(634458520)在19/05/12 22:33:03,您的余额为 SLSH44,222.62。
所以我想提取此消息的几个部分,例如
Ref:1141125019
发送量:SLSH4,000
收件人名称:AXMED XASAN WARSAME
收件人电话:634458520
日期:19/05/12
时间:22:33:03
余额:SLSH44,222.62
我已经将文本消息显示在列表视图中,现在我想对其进行自定义,我不希望整个消息都出现,我只希望上面提到的部分出现。
这是示例代码
if (Data.contains("Ref:")){
String[] Tx = Data.split("Ref:");
String TxID = Tx[1];
}
答案 0 :(得分:0)
使用正则表达式(regex)可能可以最好地解决此问题
使用正则表达式可以根据模式匹配字符串,并从字符串中提取信息。
public static void main(String[] args) {
String data = "( [-ZAAD SHILLING-] Ref:1141125019 SLSH4,000 sent to AXMED XASAN WARSAME(634458520) at 12/05/19 22:33:03, Your Balance is SLSH44,222.62. )";
String headerReg = "\\[-([a-zA-Z\\s]+?)-]";
String refReg = "Ref:([0-9]+)";
String amountReg = "([,.\\w]+)";
String nameReg = "([\\w\\s]+?)";
String accountReg = "\\([0-9]+\\)";
String dateReg = "([0-9]{2}/[0-9]{2}/[0-9]{2})";
String timeReg = "([0-9]{2}:[0-9]{2}:[0-9]{2})";
String balanceReg = "([,.\\w]+?)";
String finalReg = "\\( " + headerReg + " " + refReg + " " + amountReg + " sent to " + nameReg + accountReg + " at " + dateReg + " " + timeReg + ", Your Balance is " + balanceReg + ". \\)";
Pattern pattern = Pattern.compile(finalReg);
Matcher matcher = pattern.matcher(data);
if (matcher.find()) {
MatchResult result = matcher.toMatchResult();
int groups = result.groupCount();
for (int i = 0; i < groups; i++) {
System.out.println(result.group(i + 1));
}
}
}
使用此方法,我们可以从您的输入字符串中找到相关数据。
答案 1 :(得分:0)
如果消息语法始终相同,则可以使用一些复杂的拆分字符串,如下所示:
String msg = "( [-ZAAD SHILLING-] Ref:1141125019 SLSH4,000 sent to AXMED XASAN WARSAME(634458520) at 12/05/19 22:33:03, Your Balance is SLSH44,222.62. )";
String ref = msg.split("Ref:")[1].split(" ")[0];
String amount = msg.split("Ref:")[1].split(" ")[1].split(" ")[0];
String recipient = msg.split("Ref:")[1].split("sent to ")[1].split("\\(")[0];
String phone = msg.split("Ref:")[1].split("sent to ")[1].split("\\(")[1].split("\\)")[0];
String date = msg.split("Ref:")[1].split("sent to ")[1].split("\\(")[1].split(" at ")[1].split(" ")[0];
String time = msg.split("Ref:")[1].split("sent to ")[1].split("\\(")[1].split(" at ")[1].split(" ")[1].split(",")[0];
String balance = msg.split("Your Balance is ")[1].split("\\)")[0];
System.out.println("ref: "+ref);
System.out.println("amount: "+amount);
System.out.println("recipient: "+recipient);
System.out.println("phone: "+phone);
System.out.println("date: "+date);
System.out.println("time: "+time);
System.out.println("balance: "+balance);
结果是:
ref: 1141125019
amount: SLSH4,000
recipient: AXMED XASAN WARSAME
phone: 634458520
date: 12/05/19
time: 22:33:03
balance: SLSH44,222.62.