无法从字符串中找到matcher.group(1)

时间:2015-05-28 10:48:27

标签: regex

这是字符串:

Not enough money for withdraw of 140.82 USD. Need to fulfill bonuses of 139.82 USD. Current withdrawable amount: 2.33 USD
pattern.compile("Not enough credit for withdraw of \\d+(?:\\.\\d+)(?:\\s[A-Z]{3})?\\. Need to fulfill bonuses of \\d+(?:\\.\\d+)(?:\\s[A-Z]{3})?\\. Current withdrawable amount: \\d+(?:\\.\\d+)?");

这是我正在使用的模式,但我需要matcher.group(1)的值。谁可以给我最后一个值2.33 USD

任何人都有助于纠正我的模式。

3 个答案:

答案 0 :(得分:2)

只需添加与捕获组内最后一个数字匹配的模式。

//function 
public String getContactName(String number) {
    String name;
  if(number != null && !number.equals("")){
    // define the columns I want the query to return
    String[] projection = new String[] {
            ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.PhoneLookup._ID};

    // encode the phone number and build the filter URI
    Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));

    // query time
    Cursor cursor = _context.getContentResolver().query(contactUri, projection, null, null, null);

    if(cursor != null) {
        if (cursor.moveToFirst()) {
            name =      cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
        } 
        cursor.close();
    }
    }
    return name;
} 

此外,您还需要将模式中的pattern.compile("Not enough money for withdraw of \\d+(?:\\.\\d+)(?:\\s[A-Z]{3})?\\. Need to fulfill bonuses of \\d+(?:\\.\\d+)(?:\\s[A-Z]{3})?\\. Current withdrawable amount: (\\d+(?:\\.\\d+)?(?:\\s[A-Z]{3})?)"); ^ ^ 更改为credit

DEMO

答案 1 :(得分:0)

你通常的正则表达的原因 \d+(?:\\.\\d+)(?:\\s[A-Z]{3})?\\.对最后一组不起作用仅仅是因为它不会在一段时间内结束。 (.

\d+(?:\\.\\d+)(?:\\s[A-Z]{3})?应该可以正常使用。

答案 2 :(得分:0)

如果你知道字符串有某种格式,你不需要完全匹配整个字符串,只需要你想要的部分,你只需要一行代码,

最简单的方法是

String withdrawable = str.replaceAll(".*?([.\\d]+) USD$", "$1");

这是有效的,因为目标位于输入的末尾。对于更通用和富有表现力的方法:

String withdrawable = str.replaceAll(".*withdrawable amount: ([.\\d]+).*", "$1");
相关问题