简体   繁体   中英

C# RichTextBox Line-by-line scan

Hey Im creating my own coding language and I already have the entire application set up with save, open, close, new, etc.

In order for the "Run" part to work, I need a way to scan and test every single line in richTextBox1.

Maybe for past Java users, something along the lines of the "java-util-scanner," but easier to use for testing each line.

Does anyone know a way to do this, where a string "scannedString" would be tested as so:

if(scannedString == "#load(moduleFiles)") {
    //action here
}
string scannedStringNextLine = ???
if(scannedStringNextLine = "") {
    //action here
}

Eventually it would look more like this:

if(scannedString == "code1" || scannedString == "code2" etc... ) {
    if(scannedString == "code1") {
        //action here
    }
} else {
    //error message
}

hope this is enough information...

To get lines of code of the RichTextBox you can split the content by a new line symbol:

var lines = this.richTextBox.Text.Split('\n').ToList();

The lines are in order of appearance. Then you can go through lines in a for or foreach loop:

foreach (var line in lines)
{
    // access a line, evaluate it, etc.
}

One way to do it is to split the text on the newline charaters and then parse each line for the text you care about:

private void btnScan_Click(object sender, EventArgs e)
{
    var code = richTextBox1.Text;

    foreach (var line in code.Split(new []{'\n','\r'}, 
        StringSplitOptions.RemoveEmptyEntries))
    {
        CheckForLoad(line);
    }
}

void CheckForLoad(string line)
{
    if (string.IsNullOrWhiteSpace(line)) return;

    int i = line.IndexOf("#load");
    if (i < 0) return;

    int openParen = line.IndexOf("(", i + 1);
    if (openParen < 0) return;

    int closeParen = line.IndexOf(")", openParen + 1);
    if (closeParen < 0) return;

    string modules = line.Substring(openParen + 1, closeParen - openParen - 1);

    MessageBox.Show(string.Format("Loading modules: {0}", modules));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM