Search code examples
regexvalacapturing-group

Regex Capturing Groups in Vala


Is there such a thing? I've been looking around the Vala API and the Regex object seems to have no support for capturing groups so that I can reference them later. Is there currently any way to get around this apparent limitation? Say I'm parsing a string out of a group of strings (the contents of a file) for a given pattern like:

parameter = value

But I want the syntax to be lax so that it could also say

 parameter=value
or
parameter =   value
etc... The first idea that springs to mind is using regular expressions with capturing groups but there seems to be no support for this feature as a part of Vala right now, as far as I can see.

The only alternative I can come up with is splitting the string with a regular expression that matches whitespace so that I end up with an array I can analyze, but then again the file might not contain only "parameter = value"-like formatted lines.


Solution

  • It goes something like this. Disclaimer, this is off the top of my head:

    Regex r = /^\s*(?P<parameter>.*)\s*=\s*(?P<value>.*)\s*$/;
    MatchInfo info;
    if(r.match(the_string, 0, out info)) {
        var parameter = info.fetch_named("parameter");
        var value = info.fetch_named("value");
    }