CSharp · Console
using System;
using System.Text.RegularExpressions;
using System.Linq; // To extract properties (Value, Length) of matches.
using System.Collections.Generic; // For the Dictionary.
public class Program
{
public static void Main()
{
string strContent =
@"[Name]
Jhon
[Age]
45
[MobileNumber]
1020304050
Billing address Delivery address
Somewhere else in the Here
world India
Not India
(nothing)";
// The INI-style fields are easily parsed with Regex.
string[] fields = { "Name", "Age", "MobileNumber" };
foreach(var field in fields)
{
var match = Regex.Match(strContent, "\\["+field+"\\]\n(.*)");
if(!match.Success) continue;
Console.WriteLine(field+": "+match.Groups[1].Value);
}
// The tabular fields.
// They start with a header line containing all the field names (separated by at least 2 spaces),
// then 1 or more data lines where each field value is aligned with the corresponding field name in the header line.
// Lookup for a known field, either at the start of a line, or after a field separator of at least 2 spaces.
var headerMatch = Regex.Match(strContent, "(?:^|.* )Billing address(?: .*|$)", RegexOptions.Multiline);
// Split the line to get the individual fields.
var fieldsMatches = Regex.Matches(headerMatch.Value+" ", "([^ ](?:[^ ]+| [^ ]+)*) +", RegexOptions.Multiline);
var fieldNames = fieldsMatches.Select(m => m.Value.Trim()).ToArray();
var fieldPos = fieldsMatches.Select(m => m.Index).ToArray();
var fieldLengths = fieldsMatches.Select(m => m.Length).ToArray();
// Get the lines following the header line, until an empty line or the end of the block.
var dataLines = Regex.Match(strContent.Substring(headerMatch.Index + headerMatch.Length), "(?:\n.+)*");
// For each line, loop to isolate individual fields.
var fieldVals = new Dictionary<string, string>();
foreach(var fieldName in fieldNames)
fieldVals.Add(fieldName, "");
foreach(Match line in Regex.Matches(dataLines.Value, ".+"))
{
var fieldNum = 0;
var ls = line.Value;
foreach(var fieldName in fieldNames)
{
var pos = fieldPos[fieldNum];
var length = fieldLengths[fieldNum];
string fragment = ls.Length <= pos ? "" : ls.Substring(pos, pos + length > ls.Length ? ls.Length - pos : length);
fragment = fragment.TrimEnd();
// For multiline field values, separate each segment from the previous with a newline,
// except if it starts with a space in which case it is just the wrapped tail of the previous (à la LDIF).
var concatenator = fieldVals[fieldName].Length > 0 && fragment.Length > 0 && fragment.Substring(0, 1) != " " ? "\n" : "";
fieldVals[fieldName] += concatenator+fragment;
++fieldNum;
}
}
foreach(var field in fieldVals)
Console.WriteLine(field.Key+": "+field.Value.Replace("\n", " <newline> "));
}
}