逐行读取文本框并将其视为单独的文本

Read a textbox line by line and treat it as a separate text

这是我用来从 RichTexbox 文本绘制矩形的代码:

    try
    {
        pictureBox1.Image = null;
        bm = new Bitmap(OrgPic.Width, OrgPic.Height);

        //Location
        string spli1 = ScriptBox.Text; var p = spli1.Split('(', ')')[1];
        string spli2 = (p.ToString().Split(',', ',')[1]);

        string source = spli2;
        string loc_1 = string.Concat(source.Where(c => !char.IsWhiteSpace(c)));
        string[] coords = loc_1.Split('.');
        Point lp = new Point(int.Parse(coords[0]), int.Parse(coords[1])); ;
        Console_.Text += $"This Lines {ScriptBox.LinesCount}";
        Console_.Text += "\n" + "split1: " + spli1.ToString();
        Console_.Text += "\n" + "split2: " + loc_1.ToString();
        Console_.Text += "\n" + "cords: " + coords.ToString();
        Console_.Text += "\n" + "lp_Point: " + lp.ToString();

        //Color
        string color = ScriptBox.Text; var r = Color.FromName(color.Split('(', ',')[1]);
        string colors = (r.ToString().Split('.', ']')[1]);
        Console_.Text += "\n" + "Color final:" + colors.ToString();
        Console_.Text += "\n" + "Color Sin split:" + r.ToString();



        Color f = Color.FromName(colors);
        Pen pen = new Pen(f);
        pen.Width = 4;
        gF = Graphics.FromImage(bm);
        gF.DrawRectangle(pen, lp.X, lp.Y, 100, 60);
        pictureBox1.Image = bm;

    }
    catch (Exception)
    {

    }

我基本上是搜索 Rect.Draw 这个词,然后搜索 颜色。 [所选颜色] 和放置矩形的坐标。 问题是当我遍历整个 RichTexbox 的功能时,它只绘制了一次矩形,我不知道我是否可以解释自己。例子

代码 1:

Rect.Draw (color.red, 90.5)

这会在其各自的位置绘制红色矩形

代码 2:

Rect.Draw (color.red, 90.5)
Rect.Draw (color.green, 100.5)

代码2没有画两个矩形。只尊重第一个,如果我删除第一个,第二个是唯一的优先。

明显的解决方案:我想知道如何逐行阅读 RichTexbox 并将每一行视为单独的文本。因此按程序绘制每个矩形。

首先,RichTextBox 有一个 string[] Lines 属性 可以使用。

此外,这似乎是一个基本上乞求使用正则表达式 (regex) 的案例。根据您的代码和字符串魔术的使用,您以前可能没有听说过它,但正则表达式用于解析字符串并根据模式提取信息。也就是说,几乎正是您要在此处执行的操作。

using System.Text.RegularExpressions;

partial class Form1 : Form
{
  Regex rectRegex = null;
  private void ProcessRtf()
  {
    //init regex once.
    if(rectRegex == null)
      rectRegex = new Regex("Rect\.Draw\s*\(color\.(?<COL>[A-Za-z]+),\s+(?<POS>\d+(\.\d+)?)\)");

    foreach(string line in ScriptBox.Lines)
    {
      //for example: line = "Rect.Draw(color.red, 90.5)"
      var match = rectRegex.Match(line);
      if(match.Success)
      {
        string col = match.Groups["COL"].Value; //col = "red"
        string pos = match.Groups["POS"].Value; //pos = "90.5"

        //draw your rectangle

        break; //abort foreach loop.
      }
    }
  }
}