Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: matching quotes

by perlmonkey (Hermit)
on May 23, 2000 at 09:06 UTC ( [id://14342]=note: print w/replies, xml ) Need Help??


in reply to matching quotes

see matching comments, It has detailed code to do exactly this. Just replace the comments flags $start and $end with '"' for both of them.

This (slightly modified from merlyn's answer here) will work and is really fast:
open(FILE, "test.txt") || die; { local $/ = undef; #set to 'slurp' mode $file = <FILE>; #read entire file into $file } close FILE; $start = '"'; $end = '"'; my $inside = 0; my $oldpos = 0; while ($file =~ /(?<!\\)(\Q$start\E|\Q$end\E)/g) { if ($inside == 0) { $oldpos = pos($file) - length($start); $inside++; } else { print substr($file, $oldpos, pos($file)-$oldpos); $inside--; } }

Replies are listed 'Best First'.
RE: Re: matching quotes
by Anonymous Monk on May 24, 2000 at 00:19 UTC
    I was thinking if there is a single regex solution?
      #!/usr/bin/perl -wl use strict; my $string = 'foo "A small \"dog\" eats pie." bar "foobar"'; print $1 while $string =~ /(?<!\\)"(.*?)(?<!\\)"/gs;

      Addendum:

      Hmm. It didn't take me fifteen minutes to write this post. perlmonkey must be typing at relativistic speeds. btw--double quotes are not special in a regex; you don't need to backslash them.

      Here is a single regex inside the while loop, but it is slower:
      while ( $file =~ /((?<!\\)\".*?(?<!\\)\")/sg) { print $1; }
      Update: takshaka is correct of course. I flaked out and did not need to backslach the ", fortunatley it works just fine either way, just more clutter.

      I dont know about my relativistic typing. I guess I am just that good :) Acutally I once took a typing test and got around a -400 wpm (note the negative!) ... apparently I got docked for extensively using the backspace key. (Either that or I typed so damn fast that I overflowed the signed int ... yah, thats it, I really typed 65136 wpm, man I'm good!)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-04-23 11:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found