Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex extract from string xx:xx:xx format

Tags:

c#

regex

I am very new to programming and I have a question, I am trying to use Regex method to extract hours, minutes and seconds from a string and putting them into an array, but so far I can do it with only one number:

 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.

How do manage to read from a string 06: 11: 33, and transform these hours, minutes and seconds into an array of ints? So the resulting array would be like this:

int[] array = new int[] {n1, n2, n3}; // the n1 would be 6, n2 would be 11 and n3 would be 33

Thank you for your time in advance!

like image 446
Igor Cherkasov Avatar asked Mar 27 '20 08:03

Igor Cherkasov


1 Answers

If the input is in this format (dd:dd:dd), you actually don't need regex in this. You can use String.Split() method. For example:

string test = "23:22:21";
string []res = test.Split(':');

The res array will now contains "23", "22", "21" as its elements. You just then need to convert them into int.

like image 138
glennmark Avatar answered Oct 27 '22 01:10

glennmark