Reputation: 1
Let's say my texts are:
New York, NY is where I live.
Boston, MA is where I live.
Kentwood in the Pines, CA is where I live.
How do I extract just "New York", "Boston", "Kentwood in the Pines"
.
I can extract State name by pattern @"\b,\s(?"<"state">"\w\w)\s\w+\s\w+\s\w\s\w+"
I am using regular expression but I'm not able to figure out how to extract city names as city names can be more than two words or three.
Upvotes: 0
Views: 164
Reputation: 1577
this is want you need ..
static void Main(string[] args)
{
string exp = "New York, NY is where I live. Boston, MA is where I live. Kentwood in the Pines, CA is where I live.";
string reg = @"[\w\s]*(?=,)";
var matches = Regex.Matches(exp, reg);
foreach (Match m in matches)
{
Console.WriteLine(m.ToString());
}
Console.ReadLine();
}
Upvotes: 2
Reputation: 34802
Just substring from the beginning of the string to the first comma:
var city = input.Substring(0, input.IndexOf(','));
This will work if your format is always [City], [State] is where I live.
and [City]
never contains a comma.
Upvotes: 2