views:

43

answers:

1

Im working on a response filter. Im trying to catch all expresion: $sometext.sometext$ with the following regular expression: ^\w+?.\w+?\$

In my implementation it looks like:

public override void Write(byte[] buffer, int offset, int count)
{
    // Convert the content in buffer to a string
    string contentInBuffer = UTF8Encoding.UTF8.GetString(buffer);


    string regex=@"^\\w+?\.\w+?\$";
    RegexOptions options = RegexOptions.Multiline;

    MatchCollection matches = Regex.Matches(contentInBuffer , regex, options);
    foreach (Match match in matches)
    {
        string value = match.Value;

    }
    outputStream.Write(UTF8Encoding.UTF8.GetBytes(contentInBuffer), offset, UTF8Encoding.UTF8.GetByteCount(contentInBuffer));

}

The issue is when I write $Catch.Me$ on a aspx page It wont get caught by my regular expression in the write method. What Im I missing?

A: 

You are missing the first $ in your regex pattern. Should be: ^\$\w+?\.\w+?\$. If you use this, then it should match.

I'm sure there are others, but one way to test your .NET reg ex patterns is to use this online tester.

The other problem you might have is that ASP.NET breaks the output into multiple chunks, so your filter could be called multiple times (with each chunk that needs to be processed). That could make your regex patterns not match because the whole page is not in there together. Here are a couple of articles related to this and some solutions: Article 1 @ west-wind.com, Article 2 @ highoncoding.com.

The only other thing that might be a problem would be if the encoding is not right. In the west-wind article above, he does the following for his GetString and GetBytes methods:

Encoding encoding = HttpContext.Current.Response.ContentEncoding;
string output = encoding.GetString(..);
byte[] buffer = encoding.GetBytes(output);
patmortech
Thanks... It works when I do this test:string input = "$some.text$ <div> hej hej hej </div>"; string regex=@"^\\w+?\.\w+?\$"; RegexOptions options = RegexOptions.Multiline; MatchCollection matches = Regex.Matches(input, regex, options); foreach (Match match in matches) { string value = match.Value; }But when Im testing on "contentInBuffer" it doesent catch anything. Why?
Sune
See my revised answer.
patmortech