Extracts key-value pairs from the given string. - CSharp System

CSharp examples for System:String Convert

Description

Extracts key-value pairs from the given string.

Demo Code


using System.Text.RegularExpressions;
using System.IO;//from w ww .  j  a va2  s .  c o  m
using System.Collections.Generic;

public class Main{
        /// <summary>
		/// Extracts key-value pairs from the given string.
		/// </summary>
		/// <param name="Input">The string to extract key-value pairs from.</param>
		/// <param name="Pattern">The pattern to search. Must contain two named capturing groups.</param>
		/// <param name="KeyName">The name of the capturing group in the pattern which holds the key.</param>
		/// <param name="ValueName">The name of the capturing group in the pattern which holds the value.</param>
		/// <returns>All key-value pairs that found in the string.</returns>
		public static IEnumerable<KeyValuePair<string, string>> GetKeyValueMatches(this string Input, string Pattern, string KeyName, string ValueName) {
			Regex r = new Regex(Pattern);
			var result = r.Matches(Input);

			foreach (Match Current in result) {
				yield return new KeyValuePair<string, string> (
					Current.Groups[KeyName].Value,
					Current.Groups[ValueName].Value
				);
			}
		}
}

Related Tutorials