C#-Regex-分隔N个单词

本文关键字:单词 分隔 C#-Regex- | 更新日期: 2023-09-27 18:24:32

我需要在标准短语中捕获N个电话号码和姓名:"请写下我的电话:999999——我和维尼修斯·莱瑟达·安德里奥尼已经90岁了。"请写下我的电话:888888-迈克尔·乔丹和我已经60岁了。"

输出应该是:字符串:999999888888字符串: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输出:???

C#-Regex-分隔N个单词

这更简单:

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]);

试试这个:

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());

据我所知,你想从这个标准格式中获得姓名和电话号码。所以,只需将表达式扩展为包含第二组名称部分,然后像检索phone一样检索值。

演示