C# - 正则表达式 - 分开N个单词

时间:2015-11-26 01:46:02

标签: c# regex

我需要在标准短语中捕获N个电话号码和姓名: “请写下我的电话:999999 - Vinicius Lacerda Andrioni,我已经90岁了。” “请写下我的电话:888888 - michael jordan,我已经60岁了。”

输出应该是: string:999999,888888 字符串:Vinicius Lacerda Andrioni,michael jordan

string pattern = @"phone: (?<after>\w+)";
string input = "Please write down my phone: 999999 - Vinicius Lacerda Andrioni and I have 90 years old.";
MatchCollection matches = Regex.Matches(input, pattern);
for (int i = 0; i < matches.Count; i++)
{ 
    MessageBox.Show(matches[i].Groups["after"].ToString());
}

输出:999999 输出:???

2 个答案:

答案 0 :(得分:1)

这更简单:

String Input = "Please write down my phone: 999999 - Vinicius Lacerda Andrioni and I have 90 years old.";

String[] Results = Input.Split(new String[] {": ", "- ", " and" }, StringSplitOptions.None);

// of course you'll want to add error checking....
MessageBox.Show(Results[1]);
MessageBox.Show(Results[2]);

答案 1 :(得分:0)

试试这个:

Regex regex = new Regex(@"phone:\s?(?<phone>\w+)\s?[-]\s?(?<name>.*)\s?and");
string input = "Please write down my phone: 999999 - Vinicius Lacerda Andrioni and I have 90 years old.";
var v= regex.Match(input);
Console.WriteLine("Phone = " + v.Groups["phone"].ToString() + " Name = " + v.Groups["name"].ToString());

据我了解,您希望从此标准格式中获取名称和电话号码。因此,只需将表达式扩展为包含名称部分的第二个组,然后以与手机相同的方式检索值。

Demo