Below is an efficient runtime text parser implemented in C# for Unity. The parser adheres to the specified requirements: it handles tags in the format <tag_name parameter1="value">Text_inside_tag</tag_name>, supports unlimited nesting, outputs clean text without tags, and populates a provided list with tag objects. Each tag object includes the tag name, a dictionary of parameters, and the start and end indices (inclusive start, exclusive end) in the clean text.
The implementation is designed for linear time complexity, O(n), where n is the length of the input text, by performing a single pass through the string. It uses a stack to handle nesting and a StringBuilder for efficient string construction.
To comply with SOLID principles:
- Single Responsibility Principle: The parser is split into modular components. The
TextParser class handles the main parsing logic, while TagParser is a separate static class responsible for parsing individual tags. This separation allows each component to have a single responsibility.
- Open/Closed Principle: The design is extensible; for example, the
TextTag class can be extended or modified without changing the parser logic, and new parsing rules can be added by extending the TagParser.
- Liskov Substitution Principle: The parser uses interfaces and base classes where appropriate (e.g.,
IList<TextTag> could be used if needed, but for simplicity, a concrete list is used here).
- Interface Segregation Principle: Not heavily applicable here, but the parser avoids large interfaces by using simple method signatures.
- Dependency Inversion Principle: High-level modules (e.g., the parser) depend on abstractions (e.g., the
TextTag class and List<TextTag>), but for simplicity in this context, concrete types are used. This could be refactored to use interfaces if integrating into a larger system.
The code assumes well-formed input for simplicity (e.g., tags are properly closed, and parameters are correctly formatted with double quotes). If invalid input is encountered, exceptions are thrown for robustness. The parser is implemented as a static utility class suitable for Unity.
Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
/// <summary>
/// Represents a parsed tag with its name, parameters, and indices in the clean text.
/// </summary>
public class TextTag
{
/// <summary>
/// The name of the tag (e.g., "b" for <b>).
/// </summary>
public string Name { get; set; }
/// <summary>
/// A dictionary of parameters for the tag (e.g., { "parameter1", "value" }).
/// </summary>
public Dictionary<string, string> Parameters { get; set; } = new Dictionary<string, string>();
/// <summary>
/// The starting index (inclusive) in the clean text where the tag's content begins.
/// </summary>
public int StartIndex { get; set; }
/// <summary>
/// The ending index (exclusive) in the clean text where the tag's content ends.
/// </summary>
public int EndIndex { get; set; }
}
/// <summary>
/// A modular parser for extracting tags and clean text from input with nested tags.
/// </summary>
public static class TextParser
{
/// <summary>
/// Parses the input text, removes all tags, and populates the provided tag list with parsed tags.
/// The tag list is cleared before parsing to ensure it contains only the results of this parse.
/// </summary>
/// <param name="inputText">The input text containing tags in the format <tag_name parameter1="value">Text</tag_name>.</param>
/// <param name="tagList">A reference to a list that will be populated with parsed tags. This list is cleared before use.</param>
/// <returns>The clean text without any tags.</returns>
/// <exception cref="Exception">Thrown if the input is malformed (e.g., unclosed tags, mismatched tags).</exception>
public static string Parse(string inputText, List<TextTag> tagList)
{
if (tagList == null)
{
throw new ArgumentNullException(nameof(tagList), "The tag list cannot be null.");
}
tagList.Clear(); // Clear the list to ensure it only contains results from this parse.
var cleanTextBuilder = new StringBuilder();
var stack = new Stack<TextTag>(); // Stack to handle nested tags.
int index = 0;
int textLength = inputText.Length;
while (index < textLength)
{
if (inputText[index] == '<')
{
// Find the end of the tag (position of '>')
int tagEndIndex = inputText.IndexOf('>', index);
if (tagEndIndex == -1)
{
throw new Exception($"Unclosed tag starting at index {index}.");
}
// Extract the tag content (without '<' and '>')
string tagContent = inputText.Substring(index + 1, tagEndIndex - index - 1);
// Parse the tag
var (tagName, isClosing, attributes) = TagParser.ParseTag(tagContent);
if (isClosing)
{
// Handle closing tag
if (stack.Count == 0)
{
throw new Exception($"Closing tag without matching opening tag: {tagName}");
}
var openTag = stack.Peek();
if (openTag.Name != tagName)
{
throw new Exception($"Mismatched tags: expected {openTag.Name}, got {tagName}");
}
// Close the tag: set end index and add to the tag list
stack.Pop();
openTag.EndIndex = cleanTextBuilder.Length; // Current length is the end index (exclusive)
tagList.Add(openTag);
}
else
{
// Handle opening tag
var newTag = new TextTag { Name = tagName, Parameters = attributes };
newTag.StartIndex = cleanTextBuilder.Length; // Current length is the start index
stack.Push(newTag);
}
// Advance index past the tag (including '>')
index = tagEndIndex + 1;
}
else
{
// Find the end of the text segment (until '<' or end of string)
int nextTagIndex = inputText.IndexOf('<', index);
int endIndex = (nextTagIndex == -1) ? textLength : nextTagIndex;
// Add the text segment to the clean text
string textSegment = inputText.Substring(index, endIndex - index);
cleanTextBuilder.Append(textSegment);
// Advance index to the end of the text segment
index = endIndex;
}
}
// Check for any unclosed tags
if (stack.Count > 0)
{
throw new Exception("Unclosed tags found.");
}
return cleanTextBuilder.ToString();
}
}
/// <summary>
/// A separate module for parsing individual tags, adhering to single responsibility.
/// </summary>
public static class TagParser
{
/// <summary>
/// Parses a tag content string (extracted without '<' and '>') into its components.
/// </summary>
/// <param name="tagContent">The content of the tag (e.g., "tag_name parameter1=\"value\"" or "/tag_name").</param>
/// <returns>A tuple containing the tag name, a boolean indicating if it's a closing tag, and a dictionary of attributes.</returns>
public static (string tagName, bool isClosing, Dictionary<string, string> attributes) ParseTag(string tagContent)
{
Dictionary<string, string> attributes = new Dictionary<string, string>();
bool isClosing = tagContent.StartsWith("/");
int startIndex = isClosing ? 1 : 0; // Skip the '/' for closing tags
// Find the end of the tag name (until whitespace or end)
int endNameIndex = startIndex;
while (endNameIndex < tagContent.Length && !char.IsWhiteSpace(tagContent[endNameIndex]))
{
endNameIndex++;
}
string tagName = tagContent.Substring(startIndex, endNameIndex - startIndex).Trim();
if (!isClosing)
{
// Parse attributes from the remaining string
string attrString = tagContent.Substring(endNameIndex).Trim();
int pos = 0;
while (pos < attrString.Length)
{
// Skip whitespace
while (pos < attrString.Length && char.IsWhiteSpace(attrString[pos])) pos++;
if (pos >= attrString.Length) break;
// Find the end of the key (until '=' or whitespace)
int keyEnd = pos;
while (keyEnd < attrString.Length && attrString[keyEnd] != '=' && !char.IsWhiteSpace(attrString[keyEnd])) keyEnd++;
if (keyEnd < attrString.Length && attrString[keyEnd] == '=')
{
string key = attrString.Substring(pos, keyEnd - pos).Trim();
// Parse the value (expecting quoted string)
int valueStart = keyEnd + 1;
if (valueStart < attrString.Length && (attrString[valueStart] == '"' || attrString[valueStart] == '\''))
{
char quote = attrString[valueStart];
int valueEnd = valueStart + 1;
while (valueEnd < attrString.Length && attrString[valueEnd] != quote) valueEnd++;
if (valueEnd < attrString.Length)
{
string value = attrString.Substring(valueStart + 1, valueEnd - valueStart - 1); // Exclude quotes
attributes[key] = value;
pos = valueEnd + 1; // Move past the closing quote
}
else
{
// Unmatched quote, skip for robustness (assume well-formed input)
pos = attrString.Length;
}
}
else
{
// No quote found, skip for simplicity (assume all values are quoted)
pos = keyEnd + 1;
}
}
else
{
// No '=' found, skip the word (invalid attribute, assume well-formed)
while (pos < attrString.Length && !char.IsWhiteSpace(attrString[pos])) pos++;
}
}
}
return (tagName, isClosing, attributes);
}
}
Explanation of Key Components
- TextTag Class: Represents a single tag with its properties. This class is simple and can be extended if needed (e.g., adding more properties like tag type).
- TextParser.Parse Method: The main entry point. It iterates through the input text once, handling text segments and tags. It uses a stack to manage nesting and calculates indices based on the current length of the
StringBuilder for clean text.
- TagParser.ParseTag Method: A modular helper method in a separate static class. It parses the tag content (without
< and >) into the tag name, closing status, and attributes. This separation allows for easier testing and modification of tag parsing logic.
- Efficiency: The parser scans the input string linearly, with substring operations and index lookups being efficient. The use of
StringBuilder ensures O(1) amortized time for appending text.
- Index Handling: Start and end indices are based on the clean text. Start index is set when a tag is opened, and end index is set when closed, using the current length of the clean text builder.
- Error Handling: Exceptions are thrown for common errors like unclosed tags or mismatched tags, making the parser robust.
- Usage in Unity: This can be used in a Unity script by calling
TextParser.Parse(inputText, tagList). For example:
using UnityEngine;
using System.Collections.Generic;
public class TextParserExample : MonoBehaviour
{
void Start()
{
string inputText = "<b color=\"red\">Hello <i>world</i>!</b>";
var tagList = new List<TextTag>();
string cleanText = TextParser.Parse(inputText, tagList);
Debug.Log("Clean Text: " + cleanText); // Outputs: "Hello world!"
foreach (var tag in tagList)
{
Debug.Log($"Tag: {tag.Name}, Start: {tag.StartIndex}, End: {tag.EndIndex}, Params: {string.Join(", ", tag.Parameters)}");
// For <b>: Start=0, End=11, Params: color=red
// For <i>: Start=6, End=11 (assuming "world" is at indices 6-10 in clean text)
}
}
}
This implementation is modular, efficient, and adheres to SOLID principles by separating concerns and using abstractions where appropriate. If further customization is needed (e.g., handling single quotes or more complex attributes), it can be extended without altering the core parser.