Smokey Grindle said:
Ok I must admit I stink at regular expressions... been trying to learn
them for a while now and its not sticking how I wish it would... but I am
trying to take a very long string (about 30KB) and pull out all the dates
in it that are in mm/dd/yyyy format and put them into a collection... how
would you go about writing this regex? and then how would you move them
into a collection? thanks a lot!
Here ya go. I'm moving the results into a DateTime-array instead. But made
a Function out of it so all you have to do is pass in the string that you
want to search through and the function will return all of the VALID dates
as the DateTime-array. Note: There is no exception handling.
Private Function ParseDates(ByVal Text As String) As DateTime()
' The following pattern matches string in the format of ##/##/####. It
' does not check for invalid dates, just matches...we perform the valid
' date checks when converting them to dates anyways, so why do it here?
Dim pattern As String = _
"(?<Date>\d{2}/\d{2}/\d{4})"
' Create the ArrayList that stores the results.
Dim validDates As ArrayList = New ArrayList()
' Search the Text for the first match.
Dim match As Match = Regex.Match(Text, pattern)
' Loop through each match. End the loop when the first unsuccessful
' match occurs.
While match.Success
' Store the match for easier reference.
Dim matchText As String = match.Groups("Date").Value
' Ensure the match is a valid date. In .Net v2.0+, I'm pretty sure
' there is a DateTime.TryParse that you *should* use instead, but
' since I'm writing this using .Net v1.1, I'm using IsDate.
If IsDate(matchText)
' Parse the text as a DateTime and add the resulting DateTime
' to our ArrayList.
validDates.Add(DateTime.Parse(matchText))
End If
' Search the Text for the next match.
match = match.NextMatch()
End While
' Convert the ArrayList to an array, cast the array as a DateTime array,
' and return the resulting DateTime array.
Return DirectCast(validDates.ToArray(GetType(DateTime)), DateTime())
End Function
HTH,
Mythran