Need help with Regular Expressions

SaskiasImp

Newcomer
Joined
Aug 22, 2003
Messages
2
I'm just learning VB.NET and now Regular Expressions so please keep it simple. Here is a sample of the strings I am working with:
"15-aug-2003 20:03:13 16010630343646 00:05:28 € 0,87"
"16-aug-2003 19:01:34 16010049259163822 00:14:38 € 0,20"
"Mon, 11-Aug-2003 13:47:15 0705646712 00:03:12 € 0.08 € 0.12 € 0.14"
I've written some regular expressions to extract the date-time, phone numbers, etc but what I wanted to know is if there is a way to extract only the second occurance of a match? Currently to extract the length of the call (e.g the second occurance of - hh:mm:ss) I am using the following expression:
"(\d{2}:\d{2}:\d{2})(?=\s+[€])"

I've been reading and looking at several examples but can't see a way to easily extract only the 2n'd (or 3rd etc) match from a string.

Great Forum, LOTS of info for a struggling beginner :D
 
Last edited:
You can define matches in the regular expression and pull them out using the Matches property. A group has the syntax:
(?<Time> ... )
Where the ... is the regular expression, such as:
(?<Time>(\d{2}:\d{2}:\d{2})


C#:
Regex regex = new Regex("(?<Time>(\d{2}:\d{2}:\d{2})");
Match match = regex.Match("15-aug-2003 20:03:13 16010630343646 00:05:28 € 0,87");
if(match.Success)
{
	string time = match.Groups["Time"].Value;
}

-Ner
 
How would I use that (in VB.NET) to find the second occurance of the time? Sorry I don't really understand how to use groups like that. Here is my current test code that extracts the 2nd "time" but it relies on the "€" being found aswell.
Code:
Imports System.Text.RegularExpressions
  
        Dim str As String = "Mon, 11-Aug-2003 13:47:15		0703642742	 00:03:12		€ 0.08	€ 0.12	€ 0.14"
        Dim pattern As String = "(\d{2}:\d{2}:\d{2})(?=\s+[€])"
        Dim re As New Regex(pattern)
        Dim Length As String = re.Match(str, pattern).ToString
        Dim Day2 As Date = "#" & Length & "#"
        
        TextBox1.Text = Day2.ToString("HH:mm:ss") & " or " & Day2.TimeOfDay.TotalSeconds & " sec's"

Thanks for the help so far.
 
The object and method calls are identical in VB. You can use the Matches property instead of the Match property to get a list of all matches.

C#:
Regex regex = new Regex(@"(?<Time>(\d{2}:\d{2}:\d{2}))");
foreach(Match timeMatch in regex.Matches("15-aug-2003 20:03:13 16010630343646 00:05:28 € 0,87"))
{
	string time = timeMatch.Groups["Time"].Value;
	Debug.WriteLine(time);
}

-Nerseus
 
Back
Top