ABB.Swum.Nodes.WordNode.Parse C# (CSharp) Method

Parse() public static method

Creates a WordNode by parsing the given string representation.
public static Parse ( string source ) : WordNode
source string The string to parse the WordNode from.
return WordNode
        public static WordNode Parse(string source) {
            if(source == null) {
                throw new ArgumentNullException("source");
            }
            
            string trimmedSource = source.Trim();
            var m = Regex.Match(trimmedSource, @"^(\w*)\((\w*)\)$"); //matches <text>(<tag>)
            if(!m.Success) {
                throw new FormatException("Provided string is not a valid WordNode string representation.");
            }
            string text = m.Groups[1].Value;
            PartOfSpeechTag tag;
            if(!Enum.TryParse<PartOfSpeechTag>(m.Groups[2].Value, out tag)) {
                throw new FormatException("Invalid part-of-speech tag in string.");
            }

            return new WordNode(text, tag);
        }

Usage Example

        /// <summary>
        /// Creates a PhraseNode by parsing the given string representation.
        /// </summary>
        /// <param name="source">The string to parse the PhraseNode from.</param>
        /// <returns>A new PhraseNode.</returns>
        public static PhraseNode Parse(string source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            var words = source.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var pn    = new PhraseNode();

            foreach (var word in words)
            {
                pn.Words.Add(WordNode.Parse(word));
            }
            return(pn);
        }