如何获取特定字符的子字符串

时间:2016-01-14 16:15:44

标签: java substring

具有特定的子字符串,如:

{"access_token":"TAeJxtzLtqwzAYQOG30WJkFFk3DxpCCKkhdUKdXcjSL2NqR0ayA3n7ZujQ0o7fGY4ZvbaESKuYw3XlJGbKc9w7FzCBPlBeMy4qj8yWk17j7OyKzCPoHeNUKkkIfTF_U1BFkdXTYqY4LJO9m21EXrvnDDnE6FHSgQbFgQRMhaeY1dLhXgDFsq93FqSvpKhR1gNEY71PkPPrFT-3pfybivPl1HS35tCZ63nftk17Kuw6l3lcwWRIj9HBLxT72_ulu74dP47Fz12CYcxrepb_RbTp2d7tAOkLEB1lYw2e3ddff00f03d82e9b36211220a974ae8b56c0263120c34a25a6c40c91a7f0fd","expires_in":179,"domain":"","username":"","firstname":"","lastname":"","email":"","roles":["","",""],"":true,"":

令牌的长度是动态的,与另一个字段相同。我想做的是提取子串TAeJxtzLtqwzAYQOG30WJkFFk3DxpCCKkhdUKdXcjSL2NqR0ayA3n7ZujQ0o7fGY4ZvbaESKuYw3XlJGbKc9w7FzCBPlBeMy4qj8yWk17j7OyKzCPoHeNUKkkIfTF_U1BFkdXTYqY4LJO9m21EXrvnDDnE6FHSgQbFgQRMhaeY1dLhXgDFsq93FqSvpKhR1gNEY71PkPPrFT-3pfybivPl1HS35tCZ63nftk17Kuw6l3lcwWRIj9HBLxT72_ulu74dP47Fz12CYcxrepb_RbTp2d7tAOkLEB1lYw2e3ddff00f03d82e9b36211220a974ae8b56c0263120c34a25a6c40c91a7f0fd

因此必须提供subString函数的第二个参数来标识此字符串中的第一个“,”。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

看起来像JSON。使用像org.Json这样的JSON解析器:

import org.json.*;


JSONObject obj = new JSONObject(" your string ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("access_token");
    ......
}

答案 1 :(得分:1)

使用gson(或其他库进行JSON解析)将此JSON String解析为object或Map,如下所示:

**

答案 2 :(得分:0)

如果是json,请检查其他答案。

否则用匹配器去做吧。例如:

    String regex = ".*access_token\":\"([^\"]+)\".*";
    Pattern pattern = Pattern.compile(regex);
    String data = "{\"access_token\":\"TAeJxtzLtqwzAYQOG30WJkFFk3DxpCCKkhdUKdXcjSL2NqR0ayA3n7ZujQ0o7fGY4ZvbaESKuYw3XlJGbKc9w7FzCBPlBeMy4qj8yWk17j7OyKzCPoHeNUKkkIfTF_U1BFkdXTYqY4LJO9m21EXrvnDDnE6FHSgQbFgQRMhaeY1dLhXgDFsq93FqSvpKhR1gNEY71PkPPrFT-3pfybivPl1HS35tCZ63nftk17Kuw6l3lcwWRIj9HBLxT72_ulu74dP47Fz12CYcxrepb_RbTp2d7tAOkLEB1lYw2e3ddff00f03d82e9b36211220a974ae8b56c0263120c34a25a6c40c91a7f0fd\",\"expires_in\":179\",";

    Matcher matcher = pattern.matcher(data);
    if(matcher.matches())
        System.out.println(matcher.group(1));

正则表达式&#34;。 access_token \&#34;:\&#34;([^ \&#34;] +)\&#34;。&#34;基本上意味着匹配任何access_token&#34;:&#34;(不是&#34;)&#34;任何东西。

如果它是性能关键,那么模式编译是静态的,因为它是一个相当昂贵的操作。