Re: split : string containing brackets



On 8 Feb, 19:01, Mirco Wahab <wahab-m...@xxxxxx> wrote:
Prototype wrote:
Well, in the examples you have given, I would want the results:
'val1 , val2 , max( val3, val4 )'
$part[0]='val1'
$part[1]='val2'
$part[2]='max(val3,val4)'

All I'm looking for is to do a "simple" split parse of a string on
commas, but avoiding splitting where the comma is enclosed in some
brackets.

OK, then you may count over the brackets
within the regex. I s stupidly took some
not-so-good-parseable examples, so it
took longer. The Regex is relatively
simple (just counting), you'll get the idea.

This is my first shot:

use strict;
use warnings;

my $o;
my $reg = qr/
(?{$o=0}) \s*
(
(?: [^,()\s]+
| \((?{ $o++ })
| \)(?{ $o-- })
| (?(?{ $o }),|\s)
)+
)
[,\s]*/xs;

while( <DATA> ) {
chomp;
my @fields = /$reg/g;
print "$_\n", scalar @fields, "\n", (map " $_\n", @fields), "\n"
}

__DATA__
val1(), val2 , max(val3,val4)
(val0,val1) , val2 , max(val3,val4)
max(val3,val4), val1 , val2 , max(val3(val6,val7),val4)

Regards

M.


Thanks to all for you various comments and solutions. I'm going with
this one, as it does exactly what I need, and has taught me some neat
new regexp stuff.

P.

.



Relevant Pages

  • Re: split : string containing brackets
    ... All I'm looking for is to do a "simple" split parse of a string on ... commas, but avoiding splitting where the comma is enclosed in some ... The Regex is relatively ...
    (comp.lang.perl.misc)
  • Re: What was first done for the vehicle again is done for the home
    ... commas should be placed inside brackets, ... on the committee, all of them persons similar to himself. ... supposedly arguing about grew extraordinarily involved and abstruse, ...
    (rec.ponds)
  • Re: Subject: Re: make checkstack on m68k
    ... >> perl skills. ... can you find a nice regex? ... We'll just add empty brackets to the other ... But then the other arch regexes that capture more than ...
    (Linux-Kernel)
  • Re: Hi - Regular Expression
    ... for general validation, it's ok. ... we can find that such regex won't ... validate the comma 's position(we can insert discretionary commas in any ... Microsoft Online Support ...
    (microsoft.public.dotnet.framework.aspnet.webcontrols)
  • Re: Splitting comma-seperated items
    ... Regex is a great way to go. ... I would say that an alteration of the method, to change the commas not in the middle of quotes, so you could split, would be faster for what he is trying to do. ... i need to extract all items between commas into a string array from the following line, but there is a comma in one of the items eg "MICHEAL JACKSON, AAMC", i used String.Splitmethod but it fails. ...
    (microsoft.public.dotnet.framework.aspnet)