【问题标题】:Extract string values from a string using regex in java在java中使用正则表达式从字符串中提取字符串值
【发布时间】:2021-06-15 13:19:07
【问题描述】:

我正在尝试使用我还不太擅长的正则表达式从 android 应用程序上的消息中提取信息。

我需要的信息从以下字符串中以粗体突出显示。

PFEDDTYGD Confirmed.on 14/6/2112:46PMKsh260.00 收到>254725400049 约翰·多伊。新账户余额为 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));

【问题讨论】:

    标签: java regex


    【解决方案1】:

    您尝试的模式中有部分不在示例数据中,并且在某些部分没有匹配足够的字符。

    您可以将模式更新为 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+([^.]+)\.
    

    查看Java demoregex demo

    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
    

    【讨论】:

      猜你喜欢
      • 2014-10-17
      • 2014-08-25
      • 2010-10-14
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多