.NET Framework Bookmark and Share   
 index > Regular Expressions > Log for regex opeartion
 

Log for regex opeartion

Hi,
I would like to log the before and after replacement string/line to a log file as a part of the Regex replace operation to a text file. Is that possible? if not Is there any other way to achieve the same?
Karthik_Seshu
Yes it is, create a Match Evaluator and simply return the match found for the evaluation, but during that time log the change. Here is an example of using an evaluator in a regex replace:

string data = @"
mouseDown(1)
key(""m"")
key(""o"")
key(""n"")
key(""k"")
key(""e"")
key(""y"")
key(""\n"")
mouseDown(1)
";

string pattern = @"
(?(^key)                  # if key startst the line, absorb all keystrokes
   ((?:key\(\x22)          # Match but don't capture key(''
    (?<Press>[^\x22]+)     # Named capture Press holds keystroke
    (?:\x22\)[\r\n]+)      # Get the rest including \r\n
   )+                      # One or more
  |
   (?<Mouse>[^\r\n]+))     # Not a key.
";


Console.WriteLine( Regex.Replace( data, pattern, delegate (Match m) 
            {
                if ( string.IsNullOrEmpty( m.Groups["Mouse"].Value ) == false )
                    return m.Groups["Mouse"].Value;

                var keys = from Capture cp in m.Groups["Press"].Captures
                           select cp.Value.ToString();

                return string.Format( "keyType({0}){1}", string.Join( string.Empty, keys.ToArray() ), Environment.NewLine );
            
            }, RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline));

/* Output
mouseDown(1)
keyType(monkey\n)
mouseDown(1)

 */


William Wegerson (www.OmegaCoder.Com)
OmegaMan
Also here is another example, not for regex replace but same idea from my blog entitled: .Net Regex MatchEvaluator
William Wegerson (www.OmegaCoder.Com)
OmegaMan
I am little confused. Ok below is the line I am using

string re = @"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]";
return Regex.Replace(text, re, ""); // The text inside "text" which is an xml will have some invalid characters and that will be removed as part of this regex

I want to log the xml lines the regex is removing the invalid characters, how do i do that. Let us I want to log at "C:\log.txt"
Karthik_Seshu
Like William said, you use the MatchEvaluator delegate to point to a method that handles the replacing. It is there you can "log" the entry.
John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
JohnGrove
I would do it as two regex strings. One to capture a line and another to replace the text. But, I agree with OmegaMan's use of a MatchValidator...

            string lineRe = @"^[^\r\n]*[\r\n]+";
            string re = @"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]";
            string test = @"This is a test
this is also a test
here is a special character " + "\x06" + @"
and this is another " + "\x08" + @" in the line
";
            string testresult = "";
            StringBuilder tmp = new StringBuilder();

            bool gotOne = false;
            using (TextWriter tr = File.AppendText(@"c:\Users\Les\log.txt"))
            {
                foreach (Match mx in Regex.Matches(test, lineRe, RegexOptions.Multiline))
                {
                    gotOne = false;
                    string lineresult = Regex.Replace(mx.Value, re, delegate(Match mx2)
                    {
                        if (gotOne == false)
                        {
                            gotOne = true;
                            tr.Write("{0} {1}: {2}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString(), mx.Value);
                        }
                        return "";
                    });
                    tmp.Append(lineresult);
                }
            }
            testresult = tmp.ToString();
            Console.Write("{0}", testresult);
        }


Les Potter, Xalnix Corporation, Yet Another C# Blog
xalnix

You can use google to search for other answers

Custom Search

More Threads

• finding contents between comment tags
• Two sets of brackets? I don't get it... >_>
• help with regular expression matching (and ignoring matches)
• how to get a html table using regex
• Expression to skip lowercase characters in first word TestBook - > TBook
• matchevaluator info for vb.net
• how to NOT match text in tag
• Problem when using Regex.Split
• My regex expression is taking way too long!!!! (cpu at 50% for up to 20 seconds)
• Regex search speed