/* 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 { /// /// 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. /// /// /// Everything after a hash (#) will be ignored. /// public class LineParser { #region Public properties /// /// Gets or sets the line being parsed. /// public string Line { get { return _line; } set { _line = value; ParseLine(); } } /// /// Gets an array of fields in the line. /// public string[] Fields { get; private set; } /// /// Indicates whether the parsed /// contains fields. /// public bool HasFields { get { return Fields.Length > 0; } } #endregion #region Constructors /// /// Constructs a LineParser object without a line. /// public LineParser() { } /// /// Constructs a LineParser object with an initial . /// /// Initial line to parse. public LineParser(string line) : this() { Line = line; } #endregion #region Private methods void ParseLine() { string s = Line.Split('#')[0]; Fields = _parser .Matches(s) .Cast() .Select(m => m.Groups["match"].Value) .ToArray(); } #endregion #region Fields // Regex modified after http://stackoverflow.com/a/554068/270712 static readonly Regex _parser = new Regex(@"(?[^\s""]+)|\""(?[^""]*)"""); string _line; #endregion } }