Working with Regular Expression

Asked

Viewed 116 times

1

I would like to know what is the best way to work with regular expression, so that it becomes a code reader:

Example:

using System.Text.RegularExpression;

void LoadRegex(string filter, RichTextBox rtb, Color c){
  var RTBmatch = Regex.Matches(rtb.Text, filter);

  Color orig = rtb.SelectionColor;
  int start = rtb.SelectionStart;
  int length = rtb.SelectionLength;

  foreach(Match m in RTBmatch){
    rtb.SelectionIndex = m.Start;
    rtb.SelectionLength = m.Length;
    rtb.SelectionColor = c;
  }

  rtb.SelectionStart = start;
  rtb.SelectionLength = length;
  rtb.SelectionColor = orig;

}

Mainform.Cs:


void FormLoaded(object o, EventArgs env){
var rtb = new RichTextBox();
rtb.Text = "if _0AB0>PRESSED!TRUE";

LoadRegex("if", rtb.Text, Color.Blue");
LoadRegex("_[0-Z]", rtb.Text, Color.DarkRed);
LoadRegex("PRESSED!TRUE", rtb.Text, Color.DarkBlue);
}

Even so all this code does not work, the color of the text does not change and neither the source!

And I wanted to know some commands of REGEX/C# because I did not find any tutorial that speaks of this in English.

  • 1

    Your question was a reference, here’s a http://aurelionet.regex/guide/

1 answer

3


Your code is just having some syntax problems and some wrong property names... fixing these, works perfectly:

private void button1_Click(object sender, EventArgs e)
{
    Colorir("if", this.richTextBox1, Color.Blue);
    Colorir("_[0-Z]+", this.richTextBox1, Color.DarkRed);
    Colorir("PRESSED!TRUE", this.richTextBox1, Color.DarkBlue);
}

static void Colorir(string filter, RichTextBox rtb, Color color)
{
    var matches = Regex.Matches(rtb.Text, filter);

    Color orig = rtb.SelectionColor;
    int start = rtb.SelectionStart;
    int length = rtb.SelectionLength;

    foreach (Match m in matches)
    {
        rtb.SelectionStart = m.Index;
        rtb.SelectionLength = m.Length;
        rtb.SelectionColor = color;
    }

    rtb.SelectionStart = start;
    rtb.SelectionLength = length;
    rtb.SelectionColor = orig;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.