Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Answer: How can I find nested delimiters?

( #192935=categorized answer: print w/ replies, xml ) Need Help??

Q&A > regular expressions > How can I find nested delimiters? contributed by ignatz

Using Text::Balanced:
#!/usr/bin/perl -w use strict; use Text::Balanced "extract_delimited"; my @queries = ( qq(QUERY = "SOME QUERY WITH "" (DOUBLE QUOTES)" YEEHA), qq(Johnson looked up and said "Pie is tasty!" People in Clarkstown + liked ""Pie"".), qq("You sir are an ""A\$\@hole""!" The chipmunks were naturally sh +ocked.), qq("""No Way!""" """Way!""") ); for (@queries) { my ($extracted, $remainder, $prefix) = extract_delimited( undef, # defaults to $_ '"', # Our chosen delimiter '[^"]*', # Allow for text before the delimiter '"'); # Escape delimiter when doubled # Strip the delimiter since Text::Balanced leaves it in $extracted =~ s/^\"(.*)\"$/$1/; print; print "\n\$prefix = '$prefix'\n"; print "\$extracted = '$extracted'\n"; print "\$remainder = '$remainder'\n\n"; }
RETURNS:
QUERY = "SOME QUERY WITH "" (DOUBLE QUOTES)" YEEHA $prefix = 'QUERY = ' $extracted = 'SOME QUERY WITH "" (DOUBLE QUOTES)' $remainder = ' YEEHA' Johnson looked up and said "Pie is tasty!" People in Clarkstown liked +""Pie"". $prefix = 'Johnson looked up and said ' $extracted = 'Pie is tasty!' $remainder = ' People in Clarkstown liked ""Pie"".' "You sir are an ""A$@hole""!" The chipmunks were naturally shocked. $prefix = '' $extracted = 'You sir are an ""A$@hole""!' $remainder = ' The chipmunks were naturally shocked.' """No Way!""" """Way!""" $prefix = '' $extracted = '""No Way!""' $remainder = ' """Way!"""'
mixing double delimiters

Comment on Answer: How can I find nested delimiters?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2014-12-22 05:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (110 votes), past polls