Files
libremetaverse/Programs/examples/TestClient/Parsing.cs

88 lines
2.6 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
namespace OpenMetaverse.TestClient
{
class Parsing
{
public static string[] ParseArguments(string str)
{
List<string> list = new List<string>();
2019-10-30 20:39:56 -05:00
string current = string.Empty;
string trimmed = null;
bool withinQuote = false;
bool escaped = false;
foreach (char c in str)
{
if (c == '"')
{
if (escaped)
{
current += '"';
escaped = false;
}
else
{
current += '"';
withinQuote = !withinQuote;
}
}
else if (c == ' ' || c == '\t')
{
if (escaped || withinQuote)
{
current += c;
escaped = false;
}
else
{
trimmed = current.Trim();
if (trimmed.StartsWith("\"") && trimmed.EndsWith("\""))
{
trimmed = trimmed.Remove(0, 1);
trimmed = trimmed.Remove(trimmed.Length - 1);
trimmed = trimmed.Trim();
}
if (trimmed.Length > 0)
list.Add(trimmed);
2022-02-25 19:38:11 -06:00
current = string.Empty;
}
}
else if (c == '\\')
{
if (escaped)
{
current += '\\';
escaped = false;
}
else
{
escaped = true;
}
}
else
{
if (escaped)
2022-02-25 19:38:11 -06:00
throw new FormatException(c + " is not an escapable character.");
current += c;
}
}
trimmed = current.Trim();
if (trimmed.StartsWith("\"") && trimmed.EndsWith("\""))
{
trimmed = trimmed.Remove(0, 1);
trimmed = trimmed.Remove(trimmed.Length - 1);
trimmed = trimmed.Trim();
}
if (trimmed.Length > 0)
list.Add(trimmed);
return list.ToArray();
}
}
}