none
How find a times in a string??

    Question

  • Hi to all , i want find times in a string for example:

    string dat=  I have two times 20:21 and 06:09 ok;

    how i find 2 times in that string??

    i try:

     Regex rgx = new Regex(@"\d{2}:\d{2}");

    Match mat = rgx.Match(dat);

    mat.toString() is a first time but how view the second time?

    thanks

    Thursday, October 31, 2013 12:34 PM

Answers

  • Regex.Match matches the first occurrence of a match. You want Regex.Matches.

    Example:

    foreach (Match match in rgx.Matches(dat))
        Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index);

    • Marked as answer by kokuxx Thursday, October 31, 2013 1:45 PM
    Thursday, October 31, 2013 12:53 PM
  • Or otherwise the MatchCollection returned by Matches has a Count property:

    int numberMatches = rgx.Matches(dat).Count;
    • Edited by tnw Thursday, October 31, 2013 3:52 PM
    • Marked as answer by kokuxx Saturday, November 02, 2013 8:20 AM
    Thursday, October 31, 2013 3:51 PM

All replies

  • Regex.Match matches the first occurrence of a match. You want Regex.Matches.

    Example:

    foreach (Match match in rgx.Matches(dat))
        Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index);

    • Marked as answer by kokuxx Thursday, October 31, 2013 1:45 PM
    Thursday, October 31, 2013 12:53 PM
  • thanks, but if i want only know how many times Time have the string ? i dont find count

    for example: 

    string dat=  I have two times 20:21 and 06:09 ok; 

    here have 2 times

    Thursday, October 31, 2013 1:49 PM
  • ok no problem i insert a variable in the foreach :)
    Thursday, October 31, 2013 2:27 PM
  • Or otherwise the MatchCollection returned by Matches has a Count property:

    int numberMatches = rgx.Matches(dat).Count;
    • Edited by tnw Thursday, October 31, 2013 3:52 PM
    • Marked as answer by kokuxx Saturday, November 02, 2013 8:20 AM
    Thursday, October 31, 2013 3:51 PM