Search code examples
.netregexstringparsingnamevaluecollection

Regex Help, Parse into NameValueCollection


I'm having an issue with RegEx. I receive a string that needs to be parsed into a NameValueCollection. ParseQueryString doesn't work because (1) the string is space delimited and (2) the values can contain spaces. I have no control over the input.

Example String:

-AppCode='MyApplication' -AppVers='V-2016.0 Debug' -MachUuid='2C850880-34FD-12F3-A06B-7336B0C4BC55' -MachName='ABEZG-F05507' -Language=2055

String values that can contain spaces or hyphens are enclosed in single quotes. Integer values are not enclosed in quotes.

I've tried:

  • [\w\-]+=[\w\s\']+(?![\w\-]+=[\w\s\'\-])

but this doesn't allow for hyphens in the value

  • [\w\-]+=[\w\s\'\-]+(?![\w\-]+=[\w\s\'\-])

This does, but it overruns the space character.

Ideal output would be:

-AppCode MyApplication
-AppVers V-2016.0 Debug
-MachUuid 2C850880-34FD-12F3-A06B-7336B0C4BC55
-MachName ABEZG-F05507
-Language 2055

Unfortunately after all these years I still can't figure out RegEx. Any help would be appreciated!


Solution

  • You can use the following regex:

    (?<name>[\w-]+)=(?:'(?<value>[^']*)'|(?<value>\S+))
    

    See the regex demo

    The ([\w-]+) captures into Group named "name" word and hyphen characters. The (?:'(?<value>[^']*)'|(?<value>\S+)) will match either single quoted values ('[^']*') of non-whitespaces (\S+) but will place into Group with name "value" only the non-whitespaces or the contents inside the '...' excluding the quotes themselves.

    Sample C# demo:

    var str = "-AppCode='MyApplication' -AppVers='V-2016.0 Debug' -MachUuid='2C850880-34FD-12F3-A06B-7336B0C4BC55' -MachName='ABEZG-F05507' -Language=2055";
    var matches = Regex.Matches(str, @"(?<name>[\w-]+)=(?:'(?<value>[^']*)'|(?<value>\S+))")
        .Cast<Match>()
        .ToDictionary(p => p.Groups["name"].Value, p=> p.Groups["value"].Value );
    foreach (var p in matches) {
        Console.WriteLine(p.Key + ": " + p.Value);
    }
    

    Output:

    -AppCode: MyApplication
    -AppVers: V-2016.0 Debug
    -MachUuid: 2C850880-34FD-12F3-A06B-7336B0C4BC55
    -MachName: ABEZG-F05507
    -Language: 2055