in reply to Regex with lookahead
In Perl, I would use a module like Config::Tiny to parse the .ini file. This would handle different [Sections] in the .ini file. However it appears that you only have the "root", section (no name) to deal with.
I would consider a sequence of regular expressions instead of one complex regex. Something perhaps like below. In Perl sometimes it is actually faster execution wise to run a couple of regex'es on the same variable rather one complex one. In this case, as I understand it, your INI file which will only be parsed once at the start of your program (meaning that performance really doesn't matter that much for this task). I recommend forgetting this lookahead stuff, it is not needed here. Go with simple multiple statements.
Also in Perl, I recommend that you learn about the "//=" operator which can assign a default value to a variable which is undefined. $v //='default';#!/usr/bin/perl use strict; use warnings; my @example = ( 'RepeatingGroup = Waiver, Flatten, out', 'RepeatingGroup = Waiver, out', 'RepeatingGroup = Waiver, out, Flatten', 'RepeatingGroup = Waiver , in', 'RepeatingGroup = Waiver , Flatten', ); foreach my $example (@example) { $example =~ s/^RepeatingGroup =\s*//; print "This is what .ini parser says: $example\n"; my ($name,$direction,$flatten) = parseRepeatingGroup($example); print " name = $name\n". " direction = $direction\n", " flatten = $flatten\n"; } sub parseRepeatingGroup { my $value_text = shift; my ($name,$rest) = $value_text =~ /^\s*(\S+)(.*)+/; my $direction = ($value_text =~ /\bin\b/i) ? 'in' : 'out'; my $flatten = ($value_text =~ /\bFLATTEN\b/i)? 1: 0; return ($name,$direction,$flatten); } __END__ This is what .ini parser says: Waiver, Flatten, out name = Waiver, direction = out flatten = 1 This is what .ini parser says: Waiver, out name = Waiver, direction = out flatten = 0 This is what .ini parser says: Waiver, out, Flatten name = Waiver, direction = out flatten = 1 This is what .ini parser says: Waiver , in name = Waiver direction = in flatten = 0 This is what .ini parser says: Waiver , Flatten name = Waiver direction = out flatten = 1
In C, I would use a very different approach. I don't see the need for regex in the C code. There are other ways of doing this, but this is not a C or C++ forum.
|
|---|