簡體   English   中英

使用 java 中的正則表達式從字符串中提取字符串值

[英]Extract string values from a string using regex in java

我正在嘗試使用我不太擅長的正則表達式從 android 應用程序的消息中提取信息。

我需要的信息從以下字符串中以粗體突出顯示。

PFEDDTYGD Confirmed.on 14/6/21 at 12:46 PMKsh 260.00254725400049 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+([^.]+)\.

請參閱Java 演示正則表達式演示

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM