Is there any way to split this? - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Is there any way to split this?

stevelestevele Posts: 1Member
Hi...

I'm a fairly new(ish) Perl programmer, and don't do enough to stay good at it. I'm struggling with coming up with a way to do the following. I've got a file full of lines that look like the following. I

Comments

  • JonathanJonathan Posts: 2,914Member
    Hi,

    Ouch. The obvious but evil thing that comes to mind is to encode the commas that are inside the quotes and then do the split. But it'd be nice to do better. How about this?

    [code]my @bits = split /,(?![^",]+")/, $string;[/code]

    Lookahead ROCKS. The idea is that you can say "here's something that I don't want this pattern to match, but that must come after the thing that I do want to match, otherwise we fail". So we match a comma. Then we do a negative lookahead (meaning I want this to not be the case) and say that we want to fail if we see a load of things that are not commas and quotes followed by a quote.

    Well, it works if there is only one quote nested inside the quotes, but for two or more it fails. So we need to consider that case...

    [code]my @bits = split /,(?!(?:[^",]|[^"],[^"])+")/, $string;[/code]

    Which is probably starting to make your head spin and took me a good five minutes to come up with. But it appears to work.

    [code]my $string = <<TEXT;
    blah,"blah, blah, blah",blah,"blah"
    TEXT

    my @bits = split /,(?!(?:[^",]|[^"],[^"])+")/, $string;
    print join "
    ", @bits;[/code]

    Run it and you get the output:

    [code]blah
    "blah, blah, blah"
    blah
    "blah"[/code]

    Hope it works for you!

    Jonathan
    ###
    for(74,117,115,116){$::a.=chr};(($_.='qwertyui')&&
    (tr/yuiqwert/her anot/))for($::b);for($::c){$_.=$^X;
    /(p.{2}l)/;$_=$1}$::b=~/(..)$/;print("$::a$::b $::c hack$1.");
Sign In or Register to comment.