0

My game has to use a text file to give it instructions in a specific order, so the files are full of symbols. In my script, I import a TextAsset with Resources.Load, and split that object by newlines into an array with this command:

string[] lines = Regex.Split(theTextObject.text, "\n|\r|\n\r");

Then, I run those lines (with a for loop) through this switch-case statement:

switch(lines[i])
{
    case "-":
        //Code
        break;
    case "+":
        //Code
        break;
    case "/":
        //Code
        break;
    case "!":
        //Code
        break;
    default:
        Debug.Log("Fell out at line " + lines[i]);
}

This technically works, but the Regex statement doesn't actually seperate it correctly. Between each line, it adds a completely blank string to the array, making a segment of it look like:

{"+", "", "-", "", "/", "", "!", ""}

Instead of

{"+", "-", "/", "!"}

So, I fixed that issue by changing the Regex.Split operator to just "\n", making it look like:

string[] lines = Regex.Split(theTextObject.text, "\n");

That makes it look right, with each line correctly seperating into the array, and no empty strings. The problem is, the switch-case statement no longer works. At all. Each line goes to the default and doesn't get matched against the cases. My log statement confirms that:

Fell out at line +

Fell out at line -

Fell out at line / etc.

Those symbols perfectly match the cases are checking for, but without those empty lines the cases don't work. How do I fix this?

Community
  • 1
  • 1
Gus Lindell
  • 246
  • 1
  • 5
  • You shouldn't use regex to split newlines, see [Easiest way to split a string on newlines in .NET](https://stackoverflow.com/questions/1547476/easiest-way-to-split-a-string-on-newlines-in-net), but I mean you could use `\r\n?|\n`. P.S. your regex is always hitting `\n` or `\r` and never `\n\r` because it's always being satisfied by one of the first options. – ctwheels Nov 28 '19 at 21:06

1 Answers1

0

@ctwheels is right. The split was messing up because my Regex was incorrect. This worked:

string[] lines = Regex.Split(patt.text, "\r\n ?|\n");
Gus Lindell
  • 246
  • 1
  • 5