Yuki Kutsuya
Yuki Kutsuya

Reputation: 4088

Only find the first match in a regex search

Regex messageServerRegex = 
    new Regex(@"([0-9\-]{10})\ ([0-9:]{8})\ \[TEXT\]\ (\[Server\])\ ([^\[]*)");

if (messageServerRegex.IsMatch(rchConsoleText))
{
    var infoMatches = messageServerRegex.Split(rchConsoleText);
    Console.WriteLine("Date: {0}\nTime: {1}\nType: {2}\nMessage: {3}",
    infoMatches[1], infoMatches[2], infoMatches[3], infoMatches[4]);
}

Here are two examples of the text we want the server to filter

2012-12-24 02:24:18 [TEXT] [Server] 2012-12-24 02:24:18 [TEXT] [Server] Sample text.

The result we want back from this line is:

Date: 2012-12-14  
Time: 02:24:18  
Type: [TEXT] [Server]  
Message: 2012-12-24 02:24:18 [TEXT] [Server] Sample text.  

But it will respond back with:

Date: 2012-12-14  
Time: 02:24:18  
Type: [TEXT] [Server]  
Message: 2012-12-24 02:24:18  

As you can see, it only shows the date and time, that's because the regex filters on that, so how do I let it only cut the date and time 1 time?

The second example works fine, which is:

2012-12-24 02:24:18 [TEXT] [Server] Sample text sample text sample text.

The result we want back from this line is:

Date: 2012-12-14  
Time: 02:24:18  
Type: [TEXT] [Server]  
Message: Sample text sample text sample text.  

Upvotes: 0

Views: 137

Answers (3)

Steve Py
Steve Py

Reputation: 34673

How about:

^([0-9\-]{10})\ ([0-9:]{8})\s*\[TEXT\]\s*\[Server\]\s*(.*)

Upvotes: 0

agent-j
agent-j

Reputation: 27913

I can't tell if your input is broken into lines. If so, it's easy to use Match.

     var inputs = new string[]{
        @"2012-12-24 02:24:18 [TEXT] [Server] 2012-12-24 02:24:18 [TEXT] [Server] Sample text.",
        @"2012-12-24 02:24:18 [TEXT] [Server] Sample text sample text sample text."};

     foreach(string input in inputs)
     {
        string pattern = @"([0-9\-]{10}) ([0-9:]{8}) \[TEXT\]\ (\[Server\]) (.*)";
        var match = Regex.Match(input, pattern);
        Console.WriteLine(
           "Date: {0}\nTime: {1}\nType: {2}\nMessage: {3}",
           match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value, match.Groups[4].Value);
     }

If not, it gets a little tougher - instead of a .* it will be a ((?!something that indicates the next entry).)

Upvotes: 2

Kyle
Kyle

Reputation: 1019

The final group in your regex excludes '[' characters which causes the text portion of the line not to match if it contains a [ character. The exclusion seems unnecesary if the input represents a single log message. Try it without the exclusion, .*, and see if that works

Upvotes: 0

Related Questions