2017-04-05 42 views
2

我是从一个URL连接得到了一块JSON文本的,目前保存到一个字符串,例如:提取最后小数

...//setting up url and connection 
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
String str = in.readLine(); 

当我打印的海峡,我找到正确的数据{"build":{"version_component":"1.0.111"}}

现在我想从str中提取111,但是我遇到了一些麻烦。

我试图 String afterLastDot = inputLine.substring(inputLine.lastIndexOf(".") + 1);

,但我最终111"}}

我需要一个解决方案是通用的,所以,如果我有String str = {"build":{"version_component":"1.0.111111111"}};解决方案仍然有效,并提取111111111(即我不想硬编码提取物中的小数点后的最后三位数字)

+0

嗯。那么你在哪里使用正则表达式? –

+0

你可以做JSON –

+1

json.getBuild.getVersion_component –

回答

0

如果您不能使用JSON解析器,那么你可以这样基于正则表达式提取:

String lastNum = str.replaceAll("^.*\\.(\\d+).*", "$1"); 

RegEx Demo

^.*是贪婪的匹配,匹配所有的东西,直到最后一个DOT和我们放入组#1中的一个或多个数字用于替换。

+0

如果str包含1.0,该怎么办。111多一次? – user648026

+1

@ user648026:OP想要提取*小数点后的最后一个数字* – anubhava

0

只是使用JSON API

JSONObject obj = new JSONObject(str); 
String versionComponent= obj.getJSONObject("build").getString("version_component"); 

然后就分开,并采取最后一个元素

versionComponent.split("\\.")[2]; 
+2

我认为OP只需要追踪111. – 2017-04-05 18:16:58

+0

这是错误的。首先,他的代码中的'str'使0感觉! –

+0

另外你给1.0.111 –

0

找到字符串的startend指标需要和:

// String str = "{"build":{"version_component":"1.0.111"}};" cannot compile without escaping 
String str = "{\"build\":{\"version_component\":\"1.0.111\"}}"; 

int start = str.lastIndexOf(".")+1; 
int end = str.lastIndexOf("\""); 
String substring = str.substring(start,end); 
+0

如果str包含1.0.111多一次呢? – user648026

-1

目前已经有一些人给了回应,但这样你可以得到你的结果

JSONObject jsonObject = new JSONObject(); 
    String str = "{\"build\":{\"version_component\":\"1.0.1111111111111111111\"}}"; 
    JSONParser parser = new JSONParser(); 
    JSONObject json = (JSONObject)parser.parse(str); 
    JSONObject jsonObj = (JSONObject)json.get("build"); 
    String json1 = (String)jsonObj.get("version_component"); 
    String data[]=json1.split("\\."); 
    System.out.println(data[2]); 
0

请,你可以试试下面的代码: ... INT指数= inputLine.lastIndexOf(“”) +1; String afterLastDot = inputLine.substring(index,index + 3);

-1

With Regular Expressions(Rexp), 你可以像这样解决你的问题;

Pattern pattern = Pattern.compile("111") ; 
Matcher matcher = pattern.matcher(str) ; 
while(matcher.find()){ 
    System.out.println(matcher.start()+" "+matcher.end()); 
    System.out.println(str.substring(matcher.start(), matcher.end())); 
} 
+0

我对硬编码答案不感兴趣,如我的问题所述 –