从字符串 xx:xx:xx 格式中提取的正则表达式

Igo*_*sov 8 c# regex

我对编程很陌生,我有一个问题,我正在尝试使用 Regex 方法从字符串中提取小时、分钟和秒并将它们放入数组中,但到目前为止我只能用一个数字来完成:

 int initialDay D = 0;
 string startDay = Console.ReadLine(); //input:  "It started 5 days ago"
 var resultString = Regex.Match(startDay, @"\d+").Value; 
 initialDay = Int32.Parse(resultString);   // initialDay here equals 5.
Run Code Online (Sandbox Code Playgroud)

如何设法从字符串 06:11:33 中读取,并将这些小时、分钟和秒转换为整数数组?所以结果数组将是这样的:

int[] array = new int[] {n1, n2, n3}; // the n1 would be 6, n2 would be 11 and n3 would be 33
Run Code Online (Sandbox Code Playgroud)

提前感谢您的时间!

小智 10

如果输入采用这种格式 (dd:dd:dd),则您实际上不需要在此使用正则表达式。您可以使用 String.Split() 方法。例如:

string test = "23:22:21";
string []res = test.Split(':');
Run Code Online (Sandbox Code Playgroud)

res 数组现在将包含“23”、“22”、“21”作为其元素。然后您需要将它们转换为 int。


Tan*_*dar 8

除非您正在尝试学习正则表达式,否则您没有理由自己执行此解析。

使用TimeSpan.Parse()此任务的方法。