in reply to removing C style comments from text files

If you want it to work across newlines, you need to do a couple things. First, make sure all the lines are in a single string. Second, if you are using . and want it to match any character including a newline, use the m//s flag. Without /s, it will match any character except a newline.

The other issue is keeping what is supposed to match the inside of the comment from matching the end, some more code, and the beginning and inside of another comment. The simple m/\/\*.*\*\//s regex will match all of "/* comment 1 */ some = code; /* comment 2 */". You tell * to match as little as possible instead of as much as possible by adding a ?, so it becomes m/\/\*.*?\*\//s.

Replies are listed 'Best First'.
Re: Re: removing C style comments from text files
by dominix (Deacon) on Jan 06, 2004 at 09:12 UTC
    so within ysth restrictions, if one wants a one-liner perl -0777 -pe 's{/\*.*?\*/}{}gs' source.c my .02
    --
    dominix
      I just tried it and it worked! I've never seen a regex contained in braces before...and what's the deal with the empty braces at the end?

      thanks!
        you can use brace in place of traditional // in match
        m{ } <=> m/ / and in searchreplace s{what}{replace}imsogxe <=> s/what/replace/imsogxe
        in perlretut you have these examples. "/World/", "m!World!", and "m{World}" all represent the same thing. so the empty Brace means "replace with nothing"
        --
        dominix
Re: Re: removing C style comments from text files
by ctp (Beadle) on Jan 06, 2004 at 18:06 UTC
    I will work with the m//s flag stuff. My original regex had the *?, but in my sample text file it didn't seem to make a difference, i.e. it wasn't acting greedy either way. thanks!