我想从短信中提取余额
我的短信内容是
account ending with ********9415 has been credited with Rs. 5000. Updated account balance is Rs. 13086.18
Your card transaction of Rs.417 is successful. Your updated credit balance is Rs.78,468
Dear Cardmember, payment of Rs.7657.00 has been received towards your Bank Credit Card ending with 3459 on 12-11-2020 through NEFT. Payment is subject to realisation. Your available Credit limit now is Rs. 173281.31.到目前为止这是我的代码
(?i)(?:\sbalance\s*)([A-Za-z0-9]+\s[A-Za-z0-9]+)
(?i)(?:\scredit limit\s*)([A-Za-z0-9]+\s[A-Za-z0-9]+)那么如何从上面的短信中获取金额呢?
发布于 2021-11-05 21:19:24
如果数据始终采用这种格式,则可以使用捕获组并匹配Rs。从示例数据:后面跟着chars and和空格:
(?i)\b(?:balance|credit\s+limit)\s+[A-Za-z]+(?:\s+[A-Za-z]+)*\s+Rs\.\s*(\d+(?:[.,]\d+)*)(?i)\b(?:balance|credit\s+limit)匹配2种备选方案之一\s+[A-Za-z]+匹配1+空格字符和1+字符A(?:\s+[A-Za-z]+)*可选择地重复前面的模式,前面是1+空格字符\s+Rs\.\s*匹配1+空格字符和Rs.(\d+(?:[.,]\d+)*)捕获组1中的.或,或1+数字可选重复的数字。String regex = "(?i)\\b(?:balance|credit\\s+limit)\\s+[A-Za-z]+(?:\\s+[A-Za-z]+)*\\s+Rs\\.\\s*(\\d+(?:[.,]\\d+)*)";
String string = "account ending with ********9415 has been credited with Rs. 5000. Updated account balance is Rs. 13086.18\n\n"
+ "Your card transaction of Rs.417 is successful. Your updated credit balance is Rs.78,468\n\n"
+ "Dear Cardmember, payment of Rs.7657.00 has been received towards your Bank Credit Card ending with 3459 on 12-11-2020 through NEFT. Payment is subject to realisation. Your available Credit limit now is Rs. 173281.31.";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(matcher.group(1));
}输出
13086.18
78,468
173281.31发布于 2021-11-05 21:18:11
您可以使用
(?i)\b(?:balance|credit\s+limit)\D+(\d+(?:[.,]\d+)?)见regex演示。详细信息
(?i) -不区分大小写的嵌入式标志选项\b -一个单词边界(?:balance|credit\s+limit) -具有任意一个或多个空白空间的balance或credit limit\D+ -一个或多个非数字字符(\d+(?:[.,]\d+)?) -第1组(需要获取的值):一个或多个数字,然后是一个可选的.或,序列和一个或多个数字。如果可能有几个点/逗号,则用?替换为*。String regex = "(?i)\\b(?:balance|credit\\s+limit)\\D+(\\d+(?:[.,]\\d+)?)";
String text = "account ending with ********9415 has been credited with Rs. 5000. Updated account balance is Rs. 13086.18\n\nYour card transaction of Rs.417 is successful. Your updated credit balance is Rs.78,468\n\nDear Cardmember, payment of Rs.7657.00 has been received towards your Bank Credit Card ending with 3459 on 12-11-2020 through NEFT. Payment is subject to realisation. Your available Credit limit now is Rs. 173281.31.";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()){
System.out.println(matcher.group(1));
} 输出:
13086.18
78,468
173281.31发布于 2021-11-05 20:58:33
这里最好避免编写复杂的regexp。很容易在其中犯错误,这样的错误很难调试。
我们所能做的是进行一系列字符串分裂,以简化问题,并将其转化为一系列较小的子问题。
Rs.中的点,以便以后的.可以用作拆分令牌。sentences数组中的每个字符串,只选择"XXX“部分之后的所有内容。这将给你的价格字符串"32.12“Double.valueOf()将其转换为一个数字即可。与使用regexp的代码相比,维护和理解这样的代码要容易得多。
https://stackoverflow.com/questions/69858945
复制相似问题