How to remove single quotes but not apostrophes in perl

I would like to know how to remove single quotes, but not apostrophes in perl.

For instance:

"Rain again!"

print

Rain again!

Many thanks

+6
source share
3 answers

If you assume that a single quote is always preceded or followed by a space, the following pair of regular expressions should work:

$line =~ s/\s'/ /g; #preceded by whitespace $line =~ s/'\s/ /g; #followed by whitespace 

you also need to consider if a line starts or ends with a single quote:

 $str =~ s/^'//; #at the start of a string $str =~ s/'$//; #at the end of a string 
+4
source

Difficult. Some single quotes appear after or before letters, but you only want to remove letters between letters. Maybe something like this using negative images:

 s/(?<![\pL\s])'|'(?![\pL\s])//g; 

Either single quotes will be deleted without letters or spaces after or before it. A lot of negatives to track there. Extended version:

 s/ (?<![\pL\s])' # no letters or whitespace before single quote | # or '(?![\pL\s]) # no letters or whitespace after single quote //gx; 

This will cover words such as, as Eli Algranti pointed out in the commentary - boys' toys and that's , but the language is always difficult to predict. For example, it is almost impossible to solve something like:

 'She looked at him and said, 'That impossible!'' 

Of course, if you expect your single quotes to appear only at the end or at the beginning of the line, you do not have to be this fantasy, you can simply delete the last and first character by any means. For example, for example, as a satellite, he simply suggested:

 s/^'|'$//g; 
+1
source
 foreach (<DATA>) { s/(:?(^\s*'|'$))//g; print; } __DATA__ 'It raining again!' 

OUTPUT

 It raining again! 

EXPLANATION

  • there is more than one way to do this
  • (:?) prevent unnecessary capture
+1
source

All Articles