Obtaining Values in a string

Hi All,

This is such a silly question, but how would i obtain the two values lat and lang in the string below, im looking at the two lat and lang values in center.

viewport: {center: {lat: 51.381443,lng: -2.357483},span: {lat: 0.089989,lng: 0.144182},


Who is Participating?
neilpriceConnect With a Mentor Commented:

You could try the following quickly knocked up regex...

(using System.Text.RegularExpressions;)

Regex r = new Regex(@".*center:.*{lat: ([-0123456789.]*),lng: ([-0123456789.]*).*lat");

Then using the r.Match(yourstring).Group[1] for lat value and r.Match(yourstring).Group[2] for lng value.
Console.WriteLine("lat=" + r.Match(@"viewport: {center: {lat: 51.381443,lng: -2.357483},span: {lat: 0.089989,lng: 0.144182},").Groups[1].ToString());
Console.WriteLine("lng=" + r.Match(@"viewport: {center: {lat: 51.381443,lng: -2.357483},span: {lat: 0.089989,lng: 0.144182},").Groups[2].ToString());

Hope this helps,
I would use regular expressions to parse the results out of the string.
Jetski5822Author Commented:
I have been trying but i jsut dont understand Regex very well, any ideas?
Mike TomlinsonMiddle School Assistant TeacherCommented:
The old fashioned way...

            String input = "viewport: {center: {lat: 51.381443,lng: -2.357483},span: {lat: 0.089989,lng: 0.144182},";

            decimal lat = 0;
            decimal lng = 0;
            int center = input.IndexOf("center:");
            int leftBrace = input.IndexOf("{", center);
            int rightBrace = input.IndexOf("}", center);
            String data = input.Substring(leftBrace + 1, rightBrace - leftBrace - 1);
            String[] values = data.Split(",".ToCharArray());          
            String[] decimalValue = values[0].Split(":".ToCharArray());
            lat = decimal.Parse(decimalValue[1]);

            decimalValue = values[1].Split(":".ToCharArray());
            lng = decimal.Parse(decimalValue[1]);

            MessageBox.Show(lat.ToString() + Environment.NewLine + lng.ToString());
Jetski5822Author Commented:
Awsome guys, thanks alot.. i changed it slightly.. as its much quicker now.

Regex regVal = new Regex(@"center: {lat: ([-0-9.]*),lng: ([-0-9.]*)},", RegexOptions.IgnoreCase|RegexOptions.Compiled);

Many thanks Nick
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.