CSharp · Console
using System;
using System.Text.RegularExpressions;
//Created by: M. Hassan
//Last Update: july, 30, 2016
//Regular expression to Parse string including non printable characters
//to capture segments of: FirstName,LastName,UserId,Password ,Date
public class Program
{
public static void Main()
{
var c = new ConfigParser();
string pw = "fg%|uy|" + '\x11' +'\x14' + "|hj" +'\x18' +"khg";
var text = Generate(pw);
Console.WriteLine("note: Password include non pintable characters and the separator |");
c.Parse(text);
Console.WriteLine("firstname: {0}", c.FirstName);
Console.WriteLine("lastname: {0}", c.LastName);
Console.WriteLine("UserId: {0}", c.UserId);
Console.WriteLine("Password: {0}", c.Password);
Console.WriteLine("date: {0}", c.Date);
}
public static string Generate(string password)
{
string text = string.Format(@"FirstName=Elmer|LastName=Fudd|UserId=EFudd|Password={0}|Date=7/29/2016", password);
return text;
}
}
class ConfigParser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserId { get; set; }
public string Password { get; set; }
public string Date { get; set; }
public ConfigParser(string text)
{
Parse(text);
}
public ConfigParser()
{
}
private static string pattern = @"
^FirstName=(?<firstname>\w+) \|
LastName=(?<lastname>\w+) \|
UserId=(?<userid>\w+) \|
Password=(?<pasword>.+) \|
Date=(?<date>.+)$
";
private Regex regex = new Regex(pattern,
RegexOptions.Singleline
| RegexOptions.ExplicitCapture
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
public void Parse(string text)
{
Console.WriteLine("text: {0}",text);
Match m = regex.Match(text);
FirstName = m.Groups["firstname"].ToString();
LastName = m.Groups["lastname"].ToString();
UserId = m.Groups["userid"].ToString();
Password = m.Groups["pasword"].ToString();
Date = m.Groups["date"].ToString();
}
}