如何使用正则表达式拆分字符串

时间:2014-05-12 14:52:54

标签: android regex

我正在使用以下代码解析json文件:

JSONObject stationJson = array.optJSONObject(i);
Station s = new Station();
s.setName(stationJson.optString("name"));
s.setTimestamp(stationJson.optString("last_update"));
s.setNumber(stationJson.optInt("number"));

这是json文件:

{
"number": 123,
"contract_name" : "7500 - London",
"name": "nom station",
"address": "adresse indicative",
}

我想在名称部分显示“伦敦”,而不是数字。

我找到了这段代码,但我不知道如何使用它:

case spots:
            number = pSpotsJSON.optString("id");
            name = pSpotsJSON.optString("name");
            address = pSpotsJSON.optString("description");
            status = pSpotsJSON.optString("status");
            displayName = buildDisplayName(name);
            break;

        default:
            throw new IllegalArgumentException("Cannot parse spots from JSON: unknown provider " + provider.getName());
    }
}
private String buildDisplayName(String name) {
    String regexp = "[\\d\\s]*([a-zA-Z](.*)$)";
    Pattern p = Pattern.compile(regexp);
    Matcher m = p.matcher(name);
    if (m.find()) {
        return m.group();
    }
    return name;
}

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

如何在String的“ - ”之后获取子字符串?

会给出这样的东西:

String contractName = stationJson.getString("contract_name");
contractName = contractName.substring(contractName.indexOf("-")+2); //+2 for the minus + space caracters