C# 使用c匹配字符串中的模式#
假设我的文本是:C# 使用c匹配字符串中的模式#,c#,regex,C#,Regex,假设我的文本是: New York, NY is where I live. Boston, MA is where I live. Kentwood in the Pines, CA is where I live. 如何提取“纽约”、“波士顿”、“松林中的肯特伍德” 我可以通过模式@“\b\s(?“\w\w)\s\w+\s\w+\s\w\s\w\s\w+” 我使用的是正则表达式,但我不知道如何提取城市名称,因为城市名称可以超过两个或三个单词。只需从字符串开头到第一个逗号的子字符串: var
New York, NY is where I live.
Boston, MA is where I live.
Kentwood in the Pines, CA is where I live.
如何提取“纽约”、“波士顿”、“松林中的肯特伍德”
我可以通过模式@“\b\s(?“\w\w)\s\w+\s\w+\s\w\s\w\s\w+”
我使用的是正则表达式,但我不知道如何提取城市名称,因为城市名称可以超过两个或三个单词。只需从字符串开头到第一个逗号的子字符串:
var city = input.Substring(0, input.IndexOf(','));
如果您的格式始终是
[City],[State]是我居住的地方,
和[City]
从不包含逗号。只需从字符串开头到第一个逗号的子字符串:
var city = input.Substring(0, input.IndexOf(','));
如果您的格式始终是
[City],[State]是我居住的地方,则此功能将起作用。
和[City]
从不包含逗号。这是您需要的
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();
}
这是你需要的
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();
}
然后从文本中删除状态名:)您可以在
,
上执行拆分,只保留之前发生的内容。这些示例非常简单。你还有更复杂的事情要处理吗?换言之,您是否遇到过没有逗号或城市名称出现在逗号前的第一个完整字符串之外的情况?然后从文本中删除州名称:)您可以在,
上执行拆分,只保留之前发生的内容。这些示例非常简单。你还有更复杂的事情要处理吗?换言之,是否存在没有逗号或城市名称出现在逗号之前的第一个完整字符串之外的其他位置的情况?