Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting 'Substitution replacement not terminated`' in my regex to replace C style comments?

Tags:

regex

perl

Trying to remove C-style comments and their delimiters. Seems straightforward but I'm spinning wheels. This is what I am trying:

$code =~ s/\/\*.+\*\//g;

However, the error I get is:

Substitution replacement not terminated

What to do?

like image 535
amphibient Avatar asked Mar 22 '13 18:03

amphibient


3 Answers

Substitution replacements take the form:

s/FIND/REPLACE/FLAGS

Note that the delimiters can be any of many characters. Therefore when dealing with patterns that include slashes, it is often better to use a different delimiter, say #.

Your substitution replacement here is missing the replace section. This is perhaps clearer if we use # instead of / as a delimiter:

$code =~ s#\/\*.+\*\/#g;

What you are probably intending to use is:

$code =~ s/\/\*.+\*\///g;

Or for clarity,

$code =~ s#/\*.+\*/##g;

Note that since # is being used as a delimiter instead, it is no longer necessary to escape /.

like image 137
Jared Ng Avatar answered Nov 01 '22 10:11

Jared Ng


You meant to write $code =~ s/\/\*.+\*\///g;

You don't have to use leaning toothpicks in your patterns:

$code =~ s{ /[*] .+ [*]/ }{}gx;

Although, you'll probably realize that this does not handle all possibilities well. For that, see How can I strip multiline C comments from a file using Perl?

like image 20
Sinan Ünür Avatar answered Nov 01 '22 10:11

Sinan Ünür


Per this thread, the following worked:

$code =~ s#/\*.*?\*/##sg;

like image 1
amphibient Avatar answered Nov 01 '22 09:11

amphibient