Mercurial > repos > IBBoard.Ini
view IniSectionParser.cs @ 5:7e06c0699257
Re #7 - Add tests to INI parsing
* Fix documentation
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sun, 18 Jan 2009 14:30:40 +0000 |
parents | 2dde4c1d19d9 |
children | f6f726c92e56 |
line wrap: on
line source
// This file (IniSectionParser.cs) is a part of the IBBoard.Ini library and is copyright 2009 IBBoard. // // The file and the library/program it is in are licensed under the GNU LGPL license. Please see COPYING.LGPL for more information and the full license. using System; using System.Text.RegularExpressions; namespace IBBoard.Ini { /// <summary> /// The IniSectionParser provides parsing of a single section from an INI file /// </summary> public class IniSectionParser { /// <summary> /// Checks whether <code>line</code> appears to be the start of a new INI section /// </summary> /// <param name="line"> /// The string to check to see if it matches the INI section header format /// </param> /// <returns> /// <code>true</code> if the string looks like an INI section header, else <code>false</code> /// </returns> public static bool IsLineStartOfNewSection(string line) { line = line.Trim(); return line.StartsWith("[") && line.EndsWith("]"); } /// <summary> /// Checks whether a string looks like an INI section by starting with a section header and zero or more lines /// </summary> /// <param name="potentialSection"> /// The string to check to see if it matches the INI section format /// </param> /// <returns> /// <code>true</code> if the string looks like an INI section, else <code>false</code> /// </returns> public static bool IsStringAnIniSection(string potentialSection) { return Regex.IsMatch(potentialSection, "^\\s*\\[[a-zA-Z0-9]+\\]\\s*(\\n|$)", RegexOptions.Multiline); } /// <summary> /// Creates an IniSection object from a string. The new line (\n) character is used to determine line breaks. /// </summary> /// <param name="sectionString"> /// The text of a section including the section header and any additional lines /// </param> /// <returns> /// An <see cref="IniSection"/> with the header and INI lines that were parsed from <code>sectionString</code> /// </returns> public static IniSection CreateSection(string sectionString) { if (!IsStringAnIniSection(sectionString)) { throw new InvalidIniSectionException("Ini section did not start with an INI header"); } string[] sectionLines = sectionString.Split('\n'); string headerLine = sectionLines[0]; string sectionName = headerLine.Trim().Substring(1, headerLine.Length - 2); IniSection section = new IniSection(sectionName); int lineCount = sectionLines.Length; for (int i = 1; i < lineCount; i++) { IIniLine iniLine = IniLineParser.ParseIniLine(sectionLines[i]); section.AddIniLine(iniLine); } return section; } } }