Tech Off Thread

6 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Searching for a RegularExpression pattern and replacing all matches

Back to Forum: Tech Off
  • User profile image
    jsampsonPC

    Hey guys,

    I'm going to write a VB.NET color-coding parser thingie for my blog, but I have zero-experience using regular expressions in VB.NET, aside from the RegularExpressionValidator.

    If I had a regular expression that Was like "^"\w$"" or however it would be written, to look for anything between two double-quotes, and then replace it with "<font color=""red"">{0}</font>", theMatch - how would I go about doing that exactly?

  • User profile image
    littleguru

    You can use this here:

    // Sample input.
    string input = "this is a keyword \"foo\" and this is another \"foo1\"";

    // Replace the content. Searches for "xxx". ? means to hold the result length minimum.
    string result = Regex.Replace(input, "\\\".+?\\\"", delegate(Match m)
    {
        return string.Format("<font color=\"red\">{0}</font>", m.Value);
    });

  • User profile image
    jsampsonPC

    Come to think of it, that won't work...especially for a line like

    Dim myString As String = "Name: " & Name.Text & ", Age: " & Age.Text

    It would turn everything, even the object name, red...
    I've got to spend some time actually thinking about these rules a little better Smiley

  • User profile image
    littleguru

    I tried this with this line:
    string input = "Dim myString As String = \"Name: \" & Name.Text & \", Age: \" & Age.Text";

    That would be your line, right? It highlighted only the "Name: " and ", Age: " part. This is the result:

    Dim myString As String = <font color="red">"Name: "</font> & Name.Text & <font color="red">", Age: "</font> & Age.Text

  • User profile image
    jsampsonPC

    Hey Guru, thanks man!

    I ended up capturing parenthesis instead, which gives the same result, but with less code - check it out:

    Regex.Replace(RichTextBox1.Text, "("".+?"")", "<font color=""red"">$0</font>")
    Where $0 prints whatever is matches the first set (in this case, the only set) of parenthesis.

    More info: http://aspnet.4guysfromrolla.com/articles/022603-1.aspx

  • User profile image
    littleguru

    jsampsonPC wrote:
    Hey Guru, thanks man!

    I ended up capturing parenthesis instead, which gives the same result, but with less code - check it out:
    Regex.Replace(RichTextBox1.Text, "("".+?"")", "<font color=""red"">$0</font>")
    Where $0 prints whatever is matches the first set (in this case, the only set) of parenthesis.

    More info: http://aspnet.4guysfromrolla.com/articles/022603-1.aspx


    Yes parentesis allow to create groups. I didn't know the $0 thing. Great to know.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.