假设我的文字是:
New York, NY is where I live.
Boston, MA is where I live.
Kentwood in the Pines, CA is where I live.
如何仅提取"New York", "Boston", "Kentwood in the Pines"
。
我可以按模式@"\b,\s(?"<"state">"\w\w)\s\w+\s\w+\s\w\s\w+"
我正在使用正则表达式,但我无法弄清楚如何提取城市名称,因为城市名称可能超过两个字或三个。
答案 0 :(得分:2)
从字符串的开头到第一个逗号的子字符串:
var city = input.Substring(0, input.IndexOf(','));
如果您的格式始终为[City], [State] is where I live.
且[City]
从不包含逗号,则此方法有效。
答案 1 :(得分:2)
这是你想要的..
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();
}