Working with Regular Expression

1

I'd like to know what is the best way to work with regular expression, so turn 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 though all this code does not work, the text color does not change nor the font!

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

    
asked by anonymous 22.02.2015 / 01:59

1 answer

3

Your code is only with some syntax problems and some wrong property names ... correcting 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;
}
    
22.02.2015 / 02:30