我正在尝试从给定文本中提取值。
以下是文字:
String 1: $.675.00 was spent on your CAPITAL ONE CREDIT Card ending 2123 on 2015-05-04:15:28:08 at Best Buy
String 2: $ 1,310.00 was spent on your Credit Card 5178XXXXXXXX6040 on MAY-04-15 at Amazon Stores.
我想从字符串中提取以下内容:
首先,我尝试从字符串中提取所有数字:我尝试了以下内容:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(string1);
Log.e("Value","from String"+m.group(0));
我总是收到以下错误:
05-05 10:09:35.532: E/AndroidRuntime(13618): java.lang.IllegalStateException: No successful match so far
05-05 10:09:35.532: E/AndroidRuntime(13618): at java.util.regex.Matcher.ensureMatch(Matcher.java:471)
05-05 10:09:35.532: E/AndroidRuntime(13618): at java.util.regex.Matcher.group(Matcher.java:578)
为什么即使文字有数字也不匹配?
谢谢!
答案 0 :(得分:1)
正如@justhecuke所说,你的字符串值没有严格的格式可以使用模式分割,所以我使用了字符串函数,试一试
String crType1 = "CREDIT Card ending ";//mind the space at end
String crType2 = "Credit Card ";//mind the space at end
String rate, cardNo, at;
if (string1.contains(crType1)) {
rate = getStringValue(string1, "$", " ");
cardNo = getStringValue(string1, crType1, " ");
at = getAddress(string1);
} else {
rate = getStringValue(string1, "$", " ");
cardNo = getStringValue(string1, crType2, " ");
at = getAddress(string1);
}
System.out.println(String.format("Rate : %s Card No : %s Address : %s", rate, cardNo, at));
方法
public static String getAddress(String string) {
return string.substring(string.lastIndexOf("at") + 2, string.length()).trim();
}
public static String getStringValue(String string, String startString, String endString) {
int startAt = string.indexOf(startString) + startString.length();
int endAt = string.indexOf(endString, startAt);
return string.substring(startAt, endAt).trim();
}
答案 1 :(得分:0)
当你致电m.group(0)
时,你还没有告诉它尝试匹配的东西。这就是为什么它会给你一个IllegalStateException。
尝试:
while(m.find()) {
Log.e("Value",String.format("From String: '%s'", m.group()));
}