zaaReloaded2/zaaReloaded2/Thesaurus/LineParser.cs

113 lines
2.9 KiB
C#
Executable File

/* LineParser.cs
* part of zaaReloaded2
*
* Copyright 2015-2017 Daniel Kraus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace zaaReloaded2.Thesaurus
{
/// <summary>
/// Simple parser that separates a line from a text file into
/// space-separated fields; field values that contain spaces must
/// be enclosed by double quotation marks.
/// </summary>
/// <remarks>
/// Everything after a hash (#) will be ignored.
/// </remarks>
public class LineParser
{
#region Public properties
/// <summary>
/// Gets or sets the line being parsed.
/// </summary>
public string Line
{
get
{
return _line;
}
set
{
_line = value;
ParseLine();
}
}
/// <summary>
/// Gets an array of fields in the line.
/// </summary>
public string[] Fields { get; private set; }
/// <summary>
/// Indicates whether the parsed <see cref="Line"/>
/// contains fields.
/// </summary>
public bool HasFields
{
get
{
return Fields.Length > 0;
}
}
#endregion
#region Constructors
/// <summary>
/// Constructs a LineParser object without a line.
/// </summary>
public LineParser() { }
/// <summary>
/// Constructs a LineParser object with an initial <paramref name="line"/>.
/// </summary>
/// <param name="line">Initial line to parse.</param>
public LineParser(string line)
: this()
{
Line = line;
}
#endregion
#region Private methods
void ParseLine()
{
string s = Line.Split('#')[0];
Fields = _parser
.Matches(s)
.Cast<Match>()
.Select(m => m.Groups["match"].Value)
.ToArray<string>();
}
#endregion
#region Fields
// Regex modified after http://stackoverflow.com/a/554068/270712
static readonly Regex _parser = new Regex(@"(?<match>[^\s""]+)|\""(?<match>[^""]*)""");
string _line;
#endregion
}
}