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

Re: Regex: Identifying comments

by Athanasius (Abbot)
on Aug 29, 2012 at 14:40 UTC ( #990487=note: print w/ replies, xml ) Need Help??


in reply to Regex: Identifying comments

Here is another approach:

#! perl use strict; use warnings; my @selects = ("select 'text' from foo --This is a comment", "select '--Not a valid comment' from foo --But t +his is", "select '--This is not a valid comment' from foo", "select '--Not this' + '--either' from foo"); for my $select (@selects) { my ($comment) = $select =~ / ( -- [^']+ ) $ /x; print $comment, "\n" if $comment; }

Output:

--This is a comment --But this is

Update: The above code does not handle single quotes in comments. The following is one way to do this (indebted to choroba’s solution, above):

#! perl use strict; use warnings; my @selects = ("select 'text' from foo --This is a comment", "select '--Not a valid comment' from foo --But t +his is", "select '--This is not a valid comment' from foo", "select '--Not this' + '--either' from foo", "select stuff from that -- a 'useful comment' goes here +?", "select 'qaws' + make from \"a\" -- comment with 'a' qu +ote", "select 'a' from 'b' with 'c' -- comment with 'a --' co +mment"); for my $select (@selects) { my $stripped = $select =~ s/ ( ' .*? ' ) /'_' x length $1/egrx; if ($stripped =~ /--/) { my $i = length($select) - (index reverse($stripped), '--') - 2 +; print substr($select, $i), "\n"; } }

Output:

--This is a comment --But this is -- a 'useful comment' goes here? -- comment with 'a' quote -- comment with 'a --' comment

Hope that helps,

Athanasius <°(((><contra mundum


Comment on Re: Regex: Identifying comments
Select or Download Code
Replies are listed 'Best First'.
Re^2: Regex: Identifying comments
by RichardK (Vicar) on Aug 29, 2012 at 15:03 UTC

    I like the look of this approach, but is this a valid comment ?

     select stuff from that -- a 'useful comment' goes here?
      Yes, as the quote comes after a free-and-clear '--'
        See the update to my reply which should handle this. It cannot handle multiline string in single quotes, though.
        لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (16)
As of 2015-07-30 13:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (271 votes), past polls