2016-01-14 90 views
0

有特定的字符串,如:如何獲得子特定字符

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

令牌的長度是動態的,同其他領域。我想要做的是提取子字符串TAeJxtzLtqwzAYQOG30WJkFFk3DxpCCKkhdUKdXcjSL2NqR0ayA3n7ZujQ0o7fGY4ZvbaESKuYw3XlJGbKc9w7FzCBPlBeMy4qj8yWk17j7OyKzCPoHeNUKkkIfTF_U1BFkdXTYqY4LJO9m21EXrvnDDnE6FHSgQbFgQRMhaeY1dLhXgDFsq93FqSvpKhR1gNEY71PkPPrFT-3pfybivPl1HS35tCZ63nftk17Kuw6l3lcwWRIj9HBLxT72_ulu74dP47Fz12CYcxrepb_RbTp2d7tAOkLEB1lYw2e3ddff00f03d82e9b36211220a974ae8b56c0263120c34a25a6c40c91a7f0fd

所以,作爲subString函數的第二個參數必須提供什麼標識該字符串中的第一個「,」。任何人可以幫忙?

回答

2

看起來像一個JSON。使用JSON解析器如org.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

使用GSON(或JSON解析另一個庫)來解析這個JSON字符串反對或來圖所示:

Gson gson = new GsonBuilder().create(); 
Type type = new TypeToken<Map<String, String>>(){}.getType(); //or use type of object of your JSON 
Map<String, String> map = gson.fromJson(yourString, type); 
String accessToken = map.get("access_token"); 
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)); 

正則表達式 「的access_token \ 」:\「([^ \ 」] +)\「。 」基本上意味着匹配任何ACCESS_TOKEN「:」(不是 「)」 任何東西。

如果性能至關重要,模式編譯爲靜態,因爲這是一個相當昂貴的操作。

相關問題