Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pattern matching comments

Status
Not open for further replies.

drkestrel

MIS
Sep 25, 2000
439
GB
I am trying to use regular expression to delete comments using
Code:
/* whatever */
in a file.

The code is as follows-
Code:
$fileContent;       #Content of file contains /* */ and 
print "BEFORE\n" . $fileContent . "\n---------------\n";
$fileContent=~ s/\/\*(.*)\*\///g;
print "AFTER \n" . $fileContent;

The 'AFTER' print out is identical to the 'BEFORE' print!

Code:
$fileContent=~ s/(\/\*)(.*)(\*\/)//g; 
gives same print out.

[code]$fileContent=~ s/(\/*)(.*)(*\/)//g;
gives error /(/*)(.*)(*/)/: ?+*{} follows nothing in regexp at comment.pl line 4.


The problem is that * and \ are both escape character, I think.
 
Code:
$fileContent=~ s#/\*[^*]*\*+([^/*][^*]*\*+)*/##g;
works, thought don't know what s# is!
 
Is this what you are trying to do? If your comment spans across multiple lines, then you need the 's' switch on the end of the s///gs. Otherwise, the regex stops at the first line ending it hits.

Code:
#!/usr/local/bin/perl

$fileContent = 'some text
/* a comment 

here */
more text after comment';

$fileContent =~ s/\/\*.*\*\///gs;
print "$fileContent\n";

HTH


keep the rudder amid ship and beware the odd typo
 
s# is the same as s/ except that it uses the # character as the delimiter, so you can use / inside the regular expression without having to escape it. If you use the s(somechar) form you can use any character you want as the delimiter. You can even use paired delimiters like:
Code:
s[...][...]
s(...)(...)
s{...}{...}
s<...><...>
Being able to use any character you want comes in very handy when your regular expressions contain slashes.

Note that this &quot;generalized&quot; for also works for matching (use m#...#) and translating (tr#...#...#). It even works for quoted strings (q[...] instead of &quot;...&quot;)!

See the perlop manpage under &quot;Quote and Quotelike Operators&quot; for more details.
Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top