1

I need to pull the city and state out string of data that look as follows:

8 mi SSW of Newtown, PA
10 mi SE of Milwaukee, WI
29 Miles E of Orlando, FL

As of right now I am passing each string individually into a method

string statusLocation = "8 mi SSW of Newtown, PA"

etc. one at a time.

What would be the best way to search this string for the city state? I was thinking either regex or substring and index of the comma etc. I wasn’t quite sure what kind of issues I would run into if a state is 3 characters or a city has a comma in it because this is Canada data as well and I am not sure how they abbreviate stuff.

4

2 に答える 2

2

あなたはすることができます

string str = "8 mi SSW of Newtown, PA";
var parts = str.Split(new[] {' '}, 5);

パーツは次のようになります:{"8"、 "mi"、 "SSW"、 "of"、 "Newtown、PA"}、parts[4]を使用して"Newtown、PA"に簡単にアクセスできます。

于 2012-05-09T19:03:14.377 に答える
0

次の正規表現を使用できます。

of (.*), ([a-zA-Z]{2})$

これにより、 の後のすべてがキャプチャofされ、コンマまで続き、その後にスペース、2 文字、そして行末が続きます。例えば:

var regex = new Regex("of (.*), ([a-zA-Z]{2})$");
var strings = new[]
                    {
                        "8 mi SSW of Newtown, PA",
                        "10 mi SE of Milwaukee, WI",
                        "29 Miles E of Orlando, FL"
                    };

foreach (var str in strings)
{
    var match = regex.Match(str);
    var city = match.Groups[1];
    var state = match.Groups[2];
    Console.Out.WriteLine("state = {0}", state);
    Console.Out.WriteLine("city = {0}", city);
}

もちろん、これは状態が 2 文字であるなど、データとのある程度の一貫性を前提としています。

于 2012-05-09T18:59:28.027 に答える