[英]Extract string values from a string using regex in java
我正在尝试使用我不太擅长的正则表达式从 android 应用程序的消息中提取信息。
我需要的信息从以下字符串中以粗体突出显示。
PFEDDTYGD Confirmed.on 14/6/21 at 12:46 PMKsh 260.00从254725400049 JOHN DOE收到。 新账户余额为 Ksh1,666。 交易成本,Ksh1
代码:PFEDDTYGD,日期:14/6/21,时间:12:46,收款:260.00,电话:254725400049 客户:JOHN DOE
这是我的代码: 注意:字符串是多行格式。
final String regex = "^([a-zA-Z0-9]+)\\s{1}[a-zA-Z0-9\\.\\s]+Ksh([0-9,.]+)\\sfrom\\s([a-zA-Z0-9\\.\\s]+)\\son\\s([0-9/]+)\\sat\\s([0-9:]+)\\s[A|P]M\\s.*$";
final String string2 = "PFEDDTYG0D Confirmed.on 14/6/21 at 12:46PMKsh260.00 received from 254725400049 JOHN DOE. New Account balance is Ksh1,666. Transaction cost, Ksh1";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string2);
if(matcher.find()) {
String code = matcher.group(1);
String amountReceived = matcher.group(2);
String from = matcher.group(3);
String date = matcher.group(4);
String time = matcher.group(5);
String format = "code: %s amount received: %s from: %s date: %s time: %s";
System.out.println(String.format(format, code, amountReceived, from, date, time));
您尝试的模式中有部分不在示例数据中,并且在某些部分不匹配足够的字符。
您可以将模式更新为 6 个捕获组,如下所示:
^([a-zA-Z0-9]+)\s+Confirmed\.on\h+(\d{1,2}/\d{1,2}/\d\d)\h+at\h+(\d{1,2}:\d{1,2})\w*Ksh(\d+(?:\.\d+)?).*?\bfrom\h+(\d+)\h+([^.]+)\.
final String regex = "^([a-zA-Z0-9]+)\\s+Confirmed\\.on\\h+(\\d{1,2}/\\d{1,2}/\\d\\d)\\h+at\\h+(\\d{1,2}:\\d{1,2})\\w*Ksh(\\d+(?:\\.\\d+)?).*?\\bfrom\\h+(\\d+)\\h+([^.]+)\\.";
final String string2 = "PFEDDTYG0D Confirmed.on 14/6/21 at 12:46PMKsh260.00 received from 254725400049 JOHN DOE. New Account balance is Ksh1,666. Transaction cost, Ksh1";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string2);
if(matcher.find()) {
String code = matcher.group(1);
String amountReceived = matcher.group(4);
String tel = matcher.group(5);
String from = matcher.group(6);
String date = matcher.group(2);
String time = matcher.group(3);
String format = "code: %s amount received: %s from: %s date: %s time: %s tel: %s";
System.out.println(String.format(format, code, amountReceived, from, date, time, tel));
}
Output
code: PFEDDTYG0D amount received: 260.00 from: JOHN DOE date: 14/6/21 time: 12:46 tel: 254725400049
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.