Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: split function for | and \| delimiter

by moritz (Cardinal)
on May 25, 2012 at 18:39 UTC ( [id://972515]=note: print w/replies, xml ) Need Help??


in reply to split function for | and \| delimiter

The most robust solution is probably to use Text::CSV, which can handle delimiters and escaped delimiters.

If you want to do it with a regex, you must split on a vertical bar that is not preceeded by a backslash.

Since both the vertical bar and the backslash are meta characters in regexes, you need to backslash-escape both:

my @chunks = split /(?<!\\)\|/, $yourstring;

See perlretut for more details.

Replies are listed 'Best First'.
Re^2: split function for | and \| delimiter
by xorl (Deacon) on May 25, 2012 at 18:52 UTC
Re^2: split function for | and \| delimiter
by darklord_999 (Acolyte) on May 25, 2012 at 19:16 UTC

    Thanks for replying. I tried your idea but it didn't work. I got the output like

    $str="9454958459|54|AWC XXX|B\|T\|MIN\|MAX\|Air Tree Reg 250 Min|Any(A +T)|455|9966004325|"; @arr=split /(?<!\\)\|/, $str; print "$_ \n" foreach(@arr);

    and the output is

    9454958459

    54

    AWC XXX

    B

    T

    MIN

    MAX

    Air Tree Reg 250 Min

    455

    9966004325

      Use single quotes to prevent interpolation of $str:
      use warnings; use strict; my $str='9454958459|54|AWC XXX|B\|T\|MIN\|MAX\|Air Tree Reg 250 Min|An +y(AT)|455|9966004325|'; my @arr=split /(?<!\\)\|/, $str; print "$_ \n" foreach(@arr); __END__ 9454958459 54 AWC XXX B\|T\|MIN\|MAX\|Air Tree Reg 250 Min Any(AT) 455 9966004325

        Yes this works. Thanks for your help :)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-19 17:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found