java - 在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));
}
输出
code: PFEDDTYG0D amount received: 260.00 from: JOHN DOE date: 14/6/21 time: 12:46 tel: 254725400049
推荐阅读
- javascript - 翻译机器人的反应收集器
- mysql - 从 MySQL 导出 MySQL 数据库,并在创建表时声明约束
- c++ - 实例的构造函数中共享指针的生命周期是多少?
- parameters - 如何在不训练 Gensim Doc2Vec 中的文档的情况下更改已保存模型的参数?
- arduino - 使按钮中断运行循环/功能
- javascript - 如何在 Google 电子表格的 Google Apps 脚本中解析 JSON
- compare - 如何删除 Shopify 中的添加到比较按钮(PORTO 主题)
- php - HTML Template PHP get Header() - 如何获取其内容?
- c++ - 从枚举编译时间函数?
- reactjs - Typescript 和 React:使用解构的事件处理程序的正确类型是什么?