Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: need to parse firts part of SQL-query (regex question)

by almut (Canon)
on Jan 17, 2008 at 16:32 UTC ( [id://662913]=note: print w/replies, xml ) Need Help??


in reply to need to parse firts part of SQL-query (regex question)

Here's a (somewhat ugly) attempt using Text::Balanced. The idea is to extract the balanced parentheses fragments, in order to apply the split to the remaining parts of the string only.

use strict; use warnings; use Text::Balanced qw(extract_bracketed); sub mysplit { my $text = shift; my @fields; do { my ($paren, $post, $pre) = extract_bracketed($text, '()', '[^( +]*'); my $s = ''; if ($pre) { $s = $pre; } elsif (!$paren) { $s = $post; $post = ''; } $s =~ s/^,//; # get rid of superfluous leading comm +a my @f = split /,/, $s; $f[-1] .= $paren if @f; # append balanced parens part to last + elem push @fields, @f; $text = $post; } while ($text); return @fields; } my $sql = "f1,f2, SUM(f3),CONCAT(f4,f5, f6), f7"; print "$_\n" for mysplit($sql);

Output:

f1 f2 SUM(f3) CONCAT(f4,f5, f6) f7

(Not well tested — also, I have that feeling there must be something more elegant than this mess of conditionals... but it's escaping me right now :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://662913]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-03-29 05:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found