Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Removing parts of text from a textfile

Discussion in 'Scripting' started by NicolasAllard, Mar 23, 2016.

  1. NicolasAllard

    NicolasAllard

    Joined:
    Nov 4, 2015
    Posts:
    10
    Hello, so i wanted to use .txt files for a dialogue system.
    The thing is, I want to b able to write stuff such as [gotoline3] on the line so the script can use this and execute it
    and I want the text to be writen without that part.

    Exemple :

    txt file:

    Hi everyone! [GoToLine7]
    Hey everyone! [GoToLine12]

    Display:

    Hi Everyone!


    So basicly all i want is to be able to put special things on my lines without them being read.

    Is there a way to remove everything between []

    THANK YOU
     
  2. MV10

    MV10

    Joined:
    Nov 6, 2015
    Posts:
    1,889
    At first I was going to suggest this:

    Code (csharp):
    1. s = s.Substring(0, s.IndexOf("[")) + s.Substring(s.IndexOf("]"));
    But then I remembered there is a Remove method available:

    Code (csharp):
    1. int start = s.IndexOf("[") + 1;
    2. s = s.Remove(start, s.IndexOf("]") - start)
    Or if you intend to discard the brackets as well:

    Code (csharp):
    1. int start = s.IndexOf("[");
    2. s = s.Remove(start, s.IndexOf("]") - start + 1)
     
  3. NicolasAllard

    NicolasAllard

    Joined:
    Nov 4, 2015
    Posts:
    10
    I will try that, and do you know if there are ways to pout commands in the text asset that my script will be able to read such as

    [goto example]
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    That code will probably work for you here, but it is somewhat limited in scope. If you think you will ever find yourself needing to parse text again, I would strongly recommend learning to use Regular Expressions. While they may be tough to get a handle on at first, there is no other tool for parsing text that comes close. You can use them in C#, and they are also useful in many other languages (basically all of them, really).
     
  5. MV10

    MV10

    Joined:
    Nov 6, 2015
    Posts:
    1,889
    Just be careful with regex, test good and bad inputs heavily. It's very easy to create something that appears simple but performs horribly. On MSDN they have an example of a simple email validation regex that can take up to an hour to process! Ah, here it is. Certainly an extreme case but real nonetheless:

    https://msdn.microsoft.com/en-us/library/gg578045(v=vs.110).aspx