为什么我的正则表达式代码不能获得字符串的这一部分?

时间:2021-07-11 20:58:14

I'm making an app that shows the user the nearest gyms. After I put in a request to the Google Places Api, it returns me some json. I get the latitude from that json using regex. However, I cannot get the longitude. My code is below. Can someone help please?

我正在制作一个应用程序,向用户显示最近的健身房。在我向Google Places Api提出请求后,它会返回一些json。我使用正则表达式从json获得纬度。但是,我无法获得经度。我的代码如下。有人可以帮忙吗?

 for (int i = 0; i < jsonArray.length(); i++){

                String latitude = "\"lat\":";
                String longitude = "lng\":";
                Pattern p = Pattern.compile(latitude +"(.*?),");
                Pattern pattern = Pattern.compile(longitude + "(.*?)"+ ",");

                JSONObject jsonPart = jsonArray.getJSONObject(i);



                String latLong = jsonPart.getString("geometry");
               Matcher m = p.matcher(jsonPart.getString("geometry"));
                Matcher matcher = pattern.matcher(jsonPart.getString("geometry"));
               while( matcher.find()) {
                   Log.i("longitude", matcher.group(1));

               }
                while (m.find()){

                    Log.i("latitude", m.group(1));
                }






            }

This is the line I need to get the latitude and longitude from. I can get the latitude, but longitude doesn't work.

这是我需要获得纬度和经度的线。我可以获得纬度,但经度不起作用。

gymlocation: {"location":{"lat":40.4434584,"lng":-79.964227}}

2 个解决方案

#1


2  

String longitude = "\"lng\":";

You are missing \"

你错过了“

Alternatively, isn't this better?

或者,这不是更好吗?

Geting json response from Google places API in android

从谷歌获取json响应将API置于android中

#2


0  

If you still want to use regex, your second expression "lng"(.*?), isn't finding anything because of the ? lazy operator. It will try to match at least characters as possible , and as the string you're searching on has no , but your expression tries to match one at the end, it will just not match anything.

如果你仍然想使用正则表达式,你的第二个表达式“lng”(。*?),由于没有找到任何东西?懒惰的算子。它将尝试尽可能匹配至少字符,并且因为您正在搜索的字符串没有,但是您的表达式尝试在最后匹配一个,它将不匹配任何内容。

#1


2  

String longitude = "\"lng\":";

You are missing \"

你错过了“

Alternatively, isn't this better?

或者,这不是更好吗?

Geting json response from Google places API in android

从谷歌获取json响应将API置于android中

#2


0  

If you still want to use regex, your second expression "lng"(.*?), isn't finding anything because of the ? lazy operator. It will try to match at least characters as possible , and as the string you're searching on has no , but your expression tries to match one at the end, it will just not match anything.

如果你仍然想使用正则表达式,你的第二个表达式“lng”(。*?),由于没有找到任何东西?懒惰的算子。它将尝试尽可能匹配至少字符,并且因为您正在搜索的字符串没有,但是您的表达式尝试在最后匹配一个,它将不匹配任何内容。