Extract string values from a string using regex in java

Viewed 49

I am trying to extract information from a message on an android application using regex which I am not quite good at yet.

The information I need is highlighted in bold from the following string.

PFEDDTYGD Confirmed.on 14/6/21 at 12:46PMKsh260.00 received from 254725400049 JOHN DOE. New Account balance is Ksh1,666. Transaction cost, Ksh1

code: PFEDDTYGD, date: 14/6/21, time:12:46, amountreceived: 260.00, phone no:254725400049 customer: JOHN DOE

here is my code: NB: the string is in multiline format.

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));
1 Answers

The pattern that you tried has parts in it that are not in the example data, and in some parts do not match enough characters.

You could update the pattern to 6 capture groups as:

^([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+([^.]+)\.

See a Java demo and a regex 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));
}

Output

code: PFEDDTYG0D amount received: 260.00 from: JOHN DOE date: 14/6/21 time: 12:46 tel: 254725400049
Related