Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Regex to do a smart split()

by flounder99 (Friar)
on Jan 30, 2004 at 19:23 UTC ( [id://325346]=note: print w/replies, xml ) Need Help??


in reply to Regex to do a smart split()

Text::CSV is nice but it doesn't work if the field is "partially" quoted.
use strict; my $line = join ",", ( '"completely quoted"', 'not quoted', 'partially "quoted"', '"completely quoted with embedded, comma"', 'partially "quoted with embedded, comma"', 'quote \'and comma, inside " single\' quote', 'single quote "and comma, inside of \' double" quote', 'last' ); my $re = qr/((?:[^"',]|"[^"]*"|'[^']*')+)/; print(">$_<\n") for $line =~ /$re/g;
outputs
>"completely quoted"< >not quoted< >partially "quoted"< >"completely quoted with embedded, comma"< >partially "quoted with embedded, comma"< >quote 'and comma, inside " single' quote< >single quote "and comma, inside of ' double" quote< >last<
it will choke on unbalanced quotes but it quick and dirty

UPDATE

it will also choke on empty fields like

one,,three

--

flounder

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-25 22:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found