Parse String and Serialise

Hello,

I have a body text that comes into my game, which I need to parse and serialise certain sections of it, due to it containing fields and values for a calculator. The text comes externally from a source, and I have no control over it. Let me show you the text body first;

---------------
Hello, this is some text.
Below you'll see a calculator

[calculator
field1="value1" field2="value2" field3="value3" field4="value4"
/]

Above is a calculator.
---------------

So firstly, I need to remove the [calculator … /] (which is a static tag) section from the text. I then need to take that removed section and parse it. The format is always;

field="value"

With only a space, or linebreak separating each entry.

I’ve been using string.Split, but it is very messy, and I’m pretty sure there are easier methods than this?

Thanks.

Sounds like a job for the mighty Regular Expression! Regex patterns can get gnarly but regex101.com is a fantastic resource to help build and debug them.

I would pull out the field1="value1" field2="value2" string in a first step, then pull the pairs from that.

Like…

using System.Text.RegularExpressions;
using UnityEngine;

[ExecuteInEditMode]
public class test : MonoBehaviour {
    private static string text = " ---------------

Hello, this is some text.
Below you’ll see a calculator

[calculator
field1="value1" field2="value2" field3="value3" field4="value4"
/]

Above is a calculator.
---------------";

    void OnEnable() {
        // look for single match of whatever's between [calculator and /]
        string pattern = @"\[calculator([^\]]*)\/\]";
        Match match = Regex.Match(text, pattern);
        if (string.IsNullOrEmpty(match.Value)) {
            Debug.LogWarning("Invalid calculator string.");
            return;
        }

        // field1="value1" field2="value2" field3="value3" field4="value4" 
        // Groups[0] is the entire match, Groups[1] is the 1st capturing group denoted by ()
        string pairs = match.Groups[1].Value.Trim();
        Debug.Log("Pairs: " + pairs);
        
        // look for multiple matches of XXXX="YYYY"
        // to escape " in an @ string replace with ""
        string pairsPattern = @"([^=]*)=""([^""]*)""";
        MatchCollection matches = Regex.Matches(pairs, pairsPattern);
        foreach (Match pairsMatch in matches) {
            string field = pairsMatch.Groups[1].Value.Trim();
            string value = pairsMatch.Groups[2].Value.Trim();
            Debug.Log(field + "=" + value);
        }
    }
}