Okay, let's design and implement an efficient, modular C# text parser for Unity that handles nested tags with parameters and provides detailed tag information.
Core Concepts & Design Decisions:
- Efficiency:
- We'll use
StringBuilder for building the clean output string to avoid excessive string allocations.
- The parsing will be done in a single pass over the input string.
- We'll avoid regular expressions for tag/attribute parsing within the loop for potentially better performance, opting for manual string manipulation.
IndexOf and Substring are generally efficient.
- Modularity & SOLID:
- SRP: Separate concerns: parsing logic, tag data representation, attribute parsing.
- DIP: Inject the attribute parser dependency into the main parser.
- ISP: Interfaces for contracts (e.g., attribute parsing).
- Tag Data: A dedicated class (
ParsedTag) to hold tag name, parameters, start/end indices, and hierarchy (parent/children).
- Hierarchy: A stack (
Stack<ParsedTag>) is the natural way to manage nested tag contexts during parsing.
- Data Structures:
ParsedTag: Stores TagName, IReadOnlyDictionary<string, string> for parameters, StartIndexInCleanText, EndIndexInCleanText, Parent (for hierarchy), Children (for hierarchy). Making parameters read-only after parsing promotes immutability.
List<ParsedTag>: The output list provided by the caller, populated as tags are successfully opened and closed.
Stack<ParsedTag>: Internal structure to track the current nesting level.
- Error Handling: Gracefully handle malformed tags (e.g., missing
>, mismatched closing tags) by treating them potentially as literal text and logging warnings, rather than crashing.
1. Interfaces and Data Structures
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents information about a parsed tag.
/// </summary>
public class ParsedTag
{
/// <summary>
/// The name of the tag (e.g., "tag_name").
/// </summary>
public string TagName { get; }
/// <summary>
/// Parameters associated with the tag. Key is parameter name, Value is parameter value.
/// </summary>
public IReadOnlyDictionary<string, string> Parameters { get; }
/// <summary>
/// The starting index of the tag's content within the *clean* (non-tagged) text.
/// </summary>
public int StartIndexInCleanText { get; private set; }
/// <summary>
/// The ending index (exclusive) of the tag's content within the *clean* (non-tagged) text.
/// Set to -1 if the tag was not properly closed.
/// </summary>
public int EndIndexInCleanText { get; private set; }
/// <summary>
/// Reference to the parent tag in the hierarchy. Null for root-level tags.
/// </summary>
public ParsedTag Parent { get; }
/// <summary>
/// Direct child tags. Useful for reconstructing the hierarchy if needed.
/// </summary>
public List<ParsedTag> Children { get; } = new List<ParsedTag>();
/// <summary>
/// Flag indicating if the tag was properly closed.
/// </summary>
public bool IsClosed => EndIndexInCleanText >= 0;
// Internal constructor used by the parser
internal ParsedTag(string tagName, IReadOnlyDictionary<string, string> parameters, ParsedTag parent)
{
TagName = tagName ?? throw new ArgumentNullException(nameof(tagName));
Parameters = parameters ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); // Ensure non-null, case-insensitive
Parent = parent;
StartIndexInCleanText = -1; // Default invalid state
EndIndexInCleanText = -1; // Default invalid state
}
// Internal method used by the parser to finalize indices
internal void SetIndices(int startIndex, int endIndex)
{
// Ensure indices are set only once and in the correct order
if (StartIndexInCleanText == -1)
{
StartIndexInCleanText = startIndex;
}
// Allow updating end index if it wasn't set or if it's a closing tag mismatch scenario (handled by parser logic)
EndIndexInCleanText = endIndex;
}
public override string ToString()
{
return $"<{TagName}{{{Parameters.Count}}}" +
(IsClosed ? $" [{StartIndexInCleanText}-{EndIndexInCleanText})" : " (OPEN)") +
(Children.Count > 0 ? $" Children:{Children.Count}" : "") + ">";
}
}
/// <summary>
/// Contract for parsing the content of a tag string (name + attributes).
/// </summary>
public interface ITagParser
{
/// <summary>
/// Parses a tag's content string (everything between '<' and '>').
/// </summary>
/// <param name="tagContent">The content inside the tag, e.g. "tag_name param1="value1" param2='value2'".</param>
/// <returns>A tuple containing the tag name and a dictionary of parameters, or null if parsing fails.</returns>
(string tagName, IReadOnlyDictionary<string, string> parameters)? Parse(string tagContent);
}
2. Attribute Parsing Implementation
This handles the extraction of the tag name and its parameters.
/// <summary>
/// Parses tag name and attributes from a tag string.
/// </summary>
public class AttributeTagParser : ITagParser
{
// Example Regex (can be complex to get perfect, manual might be faster but more code)
// Let's use a manual approach for potentially better performance and control.
public (string tagName, IReadOnlyDictionary<string, string> parameters)? Parse(string tagContent)
{
if (string.IsNullOrWhiteSpace(tagContent) || tagContent.StartsWith("/"))
{
// Not a valid opening tag format we expect here (e.g., empty or closing tag)
return null;
}
var parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
int currentIndex = 0;
// 1. Find Tag Name
int tagNameEnd = FindNextWhitespaceOrEnd(tagContent, 0);
if (tagNameEnd == 0) return null; // Tag content starts with whitespace? Invalid.
string tagName = tagContent.Substring(0, tagNameEnd).Trim();
if (string.IsNullOrEmpty(tagName)) return null; // Should not happen if tagNameEnd > 0
currentIndex = tagNameEnd;
// 2. Parse Attributes
while (currentIndex < tagContent.Length)
{
// Skip whitespace
currentIndex = SkipWhitespace(tagContent, currentIndex);
if (currentIndex >= tagContent.Length) break;
// Find attribute name start
int attrNameStart = currentIndex;
int attrNameEnd = FindNextWhitespaceOrEndOfAttribute(tagContent, attrNameStart);
string attrName = tagContent.Substring(attrNameStart, attrNameEnd - attrNameStart).Trim();
if (string.IsNullOrEmpty(attrName)) break; // End of attributes
currentIndex = attrNameEnd;
// Skip whitespace before '='
currentIndex = SkipWhitespace(tagContent, currentIndex);
if (currentIndex >= tagContent.Length || tagContent[currentIndex] != '=')
{
// Malformed attribute (no '=') or end of attributes reached unexpectedly
// Treat attribute name as potentially a boolean flag? Or ignore? Let's ignore for simplicity.
// LogWarning($"Malformed attribute: missing '=' after '{attrName}'");
// For robustness, advance past name and try next attribute
currentIndex = SkipWhitespace(tagContent, currentIndex); // Skip potential spaces after name
if (currentIndex < tagContent.Length && tagContent[currentIndex] != '<' && tagContent[currentIndex] != '/') {
// Might be another attribute name right after, try again
continue;
} else {
break; // Stop parsing attributes
}
}
// Skip '='
currentIndex++;
// Skip whitespace after '='
currentIndex = SkipWhitespace(tagContent, currentIndex);
if (currentIndex >= tagContent.Length) break; // Missing value
// Find attribute value (quoted)
char quoteChar = tagContent[currentIndex];
if (quoteChar != '\'' && quoteChar != '"')
{
// Malformed attribute value (not quoted)
// LogWarning($"Malformed attribute value: expected quote after '=' for '{attrName}'");
// Try to find next whitespace to get an unquoted value? Risky. Let's stop parsing this tag.
// Or maybe find next whitespace to treat as unquoted value
int unquotedValueEnd = FindNextWhitespaceOrEnd(tagContent, currentIndex);
string unquotedValue = tagContent.Substring(currentIndex, unquotedValueEnd - currentIndex).Trim();
parameters[attrName] = unquotedValue;
currentIndex = unquotedValueEnd;
// Continue to next attribute
continue; // Added continue for unquoted value handling
}
// Skip opening quote
currentIndex++;
int attrValueStart = currentIndex;
int attrValueEnd = tagContent.IndexOf(quoteChar, attrValueStart);
if (attrValueEnd == -1)
{
// Malformed attribute value (unterminated quote)
// LogWarning($"Malformed attribute value: unterminated quote for '{attrName}'");
// Use remaining string as value?
parameters[attrName] = tagContent.Substring(attrValueStart);
currentIndex = tagContent.Length; // End parsing
break;
}
string attrValue = tagContent.Substring(attrValueStart, attrValueEnd - attrValueStart);
parameters[attrName] = attrValue;
currentIndex = attrValueEnd;
// Skip closing quote
currentIndex++;
}
return (tagName, parameters);
}
private int SkipWhitespace(string text, int startIndex)
{
int i = startIndex;
while (i < text.Length && char.IsWhiteSpace(text[i]))
{
i++;
}
return i;
}
private int FindNextWhitespaceOrEnd(string text, int startIndex)
{
int i = startIndex;
while (i < text.Length && !char.IsWhiteSpace(text[i]))
{
i++;
}
return i;
}
// Finds whitespace, end of string, or the end quote matching the starting quote
private int FindNextWhitespaceOrEndOfAttribute(string text, int startIndex) {
int i = startIndex;
char startChar = text[startIndex]; // Could be quote or letter
if (startChar == '\'' || startChar == '"') { // This means we are parsing value not name. Let's adjust logic.
// This function should only parse the name part initially.
// Let's rename it to FindEndOfAttributeName
throw new InvalidOperationException("This helper should find end of name only.");
}
// Find end of attribute name
while (i < text.Length) {
char c = text[i];
if (char.IsWhiteSpace(c) || c == '=') {
break; // Found end of name
}
i++;
}
return i;
}
}
Self-correction: The FindNextWhitespaceOrEndOfAttribute was slightly misused in the logic above. Let's simplify the attribute parsing loop to be clearer.
Revised AttributeTagParser.Parse Method:
public class AttributeTagParser : ITagParser
{
public (string tagName, IReadOnlyDictionary<string, string> parameters)? Parse(string tagContent)
{
if (string.IsNullOrWhiteSpace(tagContent) || tagContent.StartsWith("/"))
return null;
var parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
int pos = 0;
// Find tag name
int nameEnd = SkipWhitespaceAndFindNonWhitespace(tagContent, pos);
if (nameEnd >= tagContent.Length) return null; // Empty tag content
pos = nameEnd;
int nameStart = pos;
nameEnd = FindNextWhitespaceOrEndOfTag(tagContent, pos);
string tagName = tagContent.Substring(nameStart, nameEnd - nameStart);
pos = nameEnd;
// Parse attributes
while (pos < tagContent.Length)
{
pos = SkipWhitespaceAndFindNonWhitespace(tagContent, pos);
if (pos >= tagContent.Length) break; // End of attributes
// Found potential attribute name start
int attrNameStart = pos;
int attrNameEnd = FindNextWhitespaceOrEquals(tagContent, pos);
string attrName = tagContent.Substring(attrNameStart, attrNameEnd - attrNameStart);
pos = attrNameEnd;
// Skip whitespace and check for '='
pos = SkipWhitespaceAndFindNonWhitespace(tagContent, pos);
if (pos >= tagContent.Length || tagContent[pos] != '=')
{
// No '=' found, could be boolean attribute or malformed
// Let's treat as boolean flag with empty value for simplicity, or just ignore
// parameters[attrName] = string.Empty; // Option 1: Boolean flag
// Or just continue to next potential attribute
// For this example, let's assume attributes MUST have '='
// Log warning maybe?
continue; // Skip if no '='
}
// Skip '='
pos++;
pos = SkipWhitespaceAndFindNonWhitespace(tagContent, pos);
if (pos >= tagContent.Length) break; // Unterminated attribute
// Check for quotes
char quote = tagContent[pos];
if (quote != '"' && quote != '\'')
{
// Unquoted value - find next whitespace or tag end
int unquotedValueEnd = FindNextWhitespaceOrEndOfTag(tagContent, pos);
string unquotedValue = tagContent.Substring(pos, unquotedValueEnd - pos);
parameters[attrName] = unquotedValue;
pos = unquotedValueEnd;
continue; // Move to next attribute
}
// Quoted value
pos++; // Skip opening quote
int attrValueStart = pos;
int attrValueEnd = tagContent.IndexOf(quote, attrValueStart);
if (attrValueEnd == -1)
{
// Unterminated quoted value - use rest of string
parameters[attrName] = tagContent.Substring(attrValueStart);
pos = tagContent.Length; // End parsing
break;
}
string attrValue = tagContent.Substring(attrValueStart, attrValueEnd - attrValueStart);
parameters[attrName] = attrValue;
pos = attrValueEnd + 1; // Skip closing quote
}
// Ensure tagName is not empty if attributes were parsed
if (string.IsNullOrEmpty(tagName)) return null;
return (tagName, parameters);
}
// Skips whitespace, returns index of first non-whitespace char or text.Length
private int SkipWhitespaceAndFindNonWhitespace(string text, int startIndex)
{
int i = startIndex;
while (i < text.Length && char.IsWhiteSpace(text[i]))
{
i++;
}
return i;
}
// Finds first whitespace or '=' character AFTER the current position
private int FindNextWhitespaceOrEquals(string text, int startIndex) {
int i = startIndex;
while (i < text.Length) {
char c = text[i];
if (char.IsWhiteSpace(c) || c == '=') {
break;
}
i++;
}
return i;
}
// Finds first whitespace or end of string character AFTER the current position
private int FindNextWhitespaceOrEndOfTag(string text, int startIndex) {
int i = startIndex;
while (i < text.Length) {
char c = text[i];
if (char.IsWhiteSpace(c) || c == '>') { // Check for '>' too
break;
}
i++;
}
return i;
}
}
3. The Main Parser Class
/// <summary>
/// Parses text containing nested tags, extracts clean text, and records tag information.
/// Complies with SOLID principles by depending on abstractions (ITagParser).
/// </summary>
public class EfficientTextParser
{
private readonly ITagParser _tagParser;
// Optional: Add logging mechanism here (e.g., via constructor)
// private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of the EfficientTextParser.
/// </summary>
/// <param name="tagParser">An implementation of ITagParser for attribute parsing.</param>
public EfficientTextParser(ITagParser tagParser)
{
_tagParser = tagParser ?? throw new ArgumentNullException(nameof(tagParser));
// _logger = logger ?? new ConsoleLogger(); // Example dependency injection
}
/// <summary>
/// Parses the input text.
/// </summary>
/// <param name="inputText">The text containing potentially nested tags.</param>
/// <param name="outputTagList">The list where parsed tag information will be stored.</param>
/// <returns>The clean text with all tags removed.</returns>
public string Parse(string inputText, List<ParsedTag> outputTagList)
{
if (inputText == null) return string.Empty;
if (outputTagList == null) throw new ArgumentNullException(nameof(outputTagList));
var cleanTextBuilder = new StringBuilder(inputText.Length); // Initial capacity guess
var tagStack = new Stack<ParsedTag>();
int currentCleanTextIndex = 0;
int currentIndex = 0;
while (currentIndex < inputText.Length)
{
// Find the next tag start '<'
int tagStartIndex = inputText.IndexOf('<', currentIndex);
if (tagStartIndex == -1)
{
// No more tags found, append the rest of the text
cleanTextBuilder.Append(inputText.Substring(currentIndex));
// Note: Any tags remaining on the stack are unclosed. They won't be added to outputTagList.
break;
}
// Append the text content *before* the current tag
if (tagStartIndex > currentIndex)
{
cleanTextBuilder.Append(inputText.Substring(currentIndex, tagStartIndex - currentIndex));
// Update the clean text index based on the text appended
currentCleanTextIndex += (tagStartIndex - currentIndex);
}
// Find the closing tag '>'
int tagEndIndex = inputText.IndexOf('>', tagStartIndex);
if (tagEndIndex == -1)
{
// Malformed tag: No closing '>' found. Treat '<' as literal text.
// _logger.LogWarning($"Malformed tag: No closing '>' found starting at index {tagStartIndex}. Treating '<' as literal.");
cleanTextBuilder.Append('<');
currentCleanTextIndex++; // Account for the literal '<'
currentIndex = tagStartIndex + 1; // Move past the '<'
continue; // Continue parsing from the next character
}
// Extract the content within the tag delimiters <...>
string tagContent = inputText.Substring(tagStartIndex + 1, tagEndIndex - (tagStartIndex + 1));
int tagDelimiterLength = tagEndIndex - tagStartIndex + 1; // Length of "<...>"
// Check if it's a closing tag
bool isClosingTag = tagContent.StartsWith("/");
string tagNameOrError = null;
if (isClosingTag)
{
tagNameOrError = tagContent.Substring(1).Trim(); // Extract name for closing tag
if (string.IsNullOrEmpty(tagNameOrError))
{
// Malformed closing tag "</>" treat as literal
// _logger.LogWarning($"Malformed closing tag at index {tagStartIndex}. Treating as literal.");
cleanTextBuilder.Append(inputText.Substring(tagStartIndex, tagDelimiterLength));
currentCleanTextIndex += tagDelimiterLength;
currentIndex = tagEndIndex + 1;
continue;
}
// Try to match with the tag on top of the stack
if (tagStack.Count > 0)
{
ParsedTag expectedOpeningTag = tagStack.Peek(); // Peek first to check name
// Case-insensitive comparison is often desired for tags
if (expectedOpeningTag.TagName.Equals(tagNameOrError, StringComparison.OrdinalIgnoreCase))
{
// Match found! Pop and finalize the tag.
ParsedTag closedTag = tagStack.Pop();
closedTag.SetIndices(closedTag.StartIndexInCleanText, currentCleanTextIndex); // End index is current clean index
outputTagList.Add(closedTag); // Add the completed tag to the output list
// If the stack still has items, update the parent's children list implicitly via the structure
// Or explicitly if needed:
// if (closedTag.Parent != null) {
// closedTag.Parent.Children.Add(closedTag); // This should ideally happen on push
// }
}
else
{
// Mismatch! Treat closing tag as literal text for robustness.
// _logger.LogWarning($"Mismatched closing tag: Expected </{expectedOpeningTag.TagName}> but found </{tagNameOrError}> at index {tagStartIndex}. Treating as literal.");
cleanTextBuilder.Append(inputText.Substring(tagStartIndex, tagDelimiterLength));
currentCleanTextIndex += tagDelimiterLength;
// DO NOT pop the stack here. The expectedOpeningTag is still open.
}
}
else
{
// Closing tag with no corresponding opening tag on the stack. Treat as literal.
// _logger.LogWarning($"Closing tag </{tagNameOrError}> found with no matching opening tag at index {tagStartIndex}. Treating as literal.");
cleanTextBuilder.Append(inputText.Substring(tagStartIndex, tagDelimiterLength));
currentCleanTextIndex += tagDelimiterLength;
}
}
else // It's an opening tag
{
// Parse the tag name and attributes
var parseResult = _tagParser.Parse(tagContent);
if (parseResult.HasValue)
{
string tagName = parseResult.Value.tagName;
IReadOnlyDictionary<string, string> parameters = parseResult.Value.parameters;
// Get the parent tag from the stack (if any)
ParsedTag parentTag = tagStack.Count > 0 ? tagStack.Peek() : null;
// Create the new tag object
var newTag = new ParsedTag(tagName, parameters, parentTag);
newTag.SetIndices(currentCleanTextIndex, -1); // Set start index, end index is unknown (-1)
// Add to parent's children list IF it exists (important for hierarchy)
parentTag?.Children.Add(newTag);
// Push the new tag onto the stack
tagStack.Push(newTag);
}
else
{
// Malformed opening tag. Treat '<' as literal text.
// _logger.LogWarning($"Malformed opening tag content: '{tagContent}' at index {tagStartIndex}. Treating '<' as literal.");
cleanTextBuilder.Append('<');
currentCleanTextIndex++; // Account for the literal '<'
// We still need to advance `currentIndex` past the whole tag "<...>"
}
}
// Move parser index past the processed tag "<...>"
currentIndex = tagEndIndex + 1;
}
// After loop, check if stack has remaining items (unclosed tags)
while (tagStack.Count > 0)
{
var unclosedTag = tagStack.Pop();
// _logger.LogWarning($"Tag </{unclosedTag.TagName}> was opened but not closed.");
// These tags are NOT added to outputTagList as they lack valid end indices.
}
return cleanTextBuilder.ToString();
}
}
4. Example Usage (Unity C# Script)
using UnityEngine;
using System.Collections.Generic;
public class TextParserExample : MonoBehaviour
{
// Attach this script to a GameObject in your scene.
// Assign text in the Inspector or dynamically.
[TextArea(5, 20)]
public string richText = "This is <B color='red'>bold</B> text.\n" +
"And <I>italic</I> <SIZE value='20'>with size</SIZE>.\n" +
"Nested: <COLOR name=\"blue\"><B>Blue Bold</B></COLOR>.\n" +
"Invalid: <B> Unclosed tag.\n" +
"Mismatched: <B>Text</I>";
void Start()
{
// Instantiate the parser with the concrete attribute parser
ITagParser attributeParser = new AttributeTagParser();
EfficientTextParser parser = new EfficientTextParser(attributeParser);
// List to hold the results
var parsedTags = new List<ParsedTag>();
// Perform the parsing
string cleanText = parser.Parse(richText, parsedTags);
// Output the results
Debug.Log("--- Clean Text ---");
Debug.Log(cleanText);
Debug.Log("\n--- Parsed Tags ---");
if (parsedTags.Count == 0)
{
Debug.Log("No valid tags were found or closed.");
}
else
{
foreach (var tag in parsedTags)
{
string paramsStr = tag.Parameters.Count > 0
? string.Join(", ", tag.Parameters.Select(kv => $"{kv.Key}='{kv.Value}'"))
: "No Params";
Debug.Log($"Tag: <{tag.TagName}>, Params: {{{paramsStr}}}, Range: [{tag.StartIndexInCleanText}-{tag.EndIndexInCleanText})");
// You can recursively print children if needed:
// PrintChildren(tag.Children, " ");
}
}
}
// Helper to print hierarchy (optional)
// void PrintChildren(List<ParsedTag> children, string indent) {
// foreach (var child in children) {
// string paramsStr = child.Parameters.Count > 0
// ? string.Join(", ", child.Parameters.Select(kv => $"{kv.Key}='{kv.Value}'"))
// : "No Params";
// Debug.Log($"{indent}Child: <{child.TagName}>, Params: {{{paramsStr}}}, Range: [{child.StartIndexInCleanText}-{child.EndIndexInCleanText})");
// PrintChildren(child.Children, indent + " ");
// }
// }
}
Explanation and Efficiency:
ParsedTag: Holds all necessary data. Using IReadOnlyDictionary makes parameters immutable after parsing. StartIndexInCleanText and EndIndexInCleanText are updated internally by the parser.
ITagParser & AttributeTagParser: Separates the logic for understanding the structure within a tag (<...>) from the main text traversal logic. This adheres to SRP and DIP. AttributeTagParser uses manual string searching (IndexOf, Substring, IsWhiteSpace) for potentially better performance than regex in tight loops.
EfficientTextParser:
- Single Pass: Iterates through the
inputText using currentIndex.
StringBuilder: cleanTextBuilder efficiently builds the output string.
Stack<ParsedTag>: Manages the nesting context. Peek() checks the current parent, Pop() finalizes a tag when its closing counterpart is found.
- Index Tracking:
currentCleanTextIndex accurately tracks the position in the conceptual clean text string as the parser progresses.
- Robustness: Handles missing
>, mismatched closing tags, and empty tags by treating delimiters or malformed sections as literal text, preventing crashes. Unclosed tags are ignored in the final outputTagList because they lack an end index.
- Output: The
outputTagList is populated only with tags that were successfully opened and closed, containing their respective ranges in the clean text.
This structure provides a clean, efficient, and maintainable solution for parsing tagged text in C# for Unity.