Search code examples
regexstringperlsingle-quotes

perl regex remove quotes from string


I would like to remove trailing and leading single quotes from a string, but not if a quote starts in the middle of the string.

Example: I would like to remove the quotes from 'text is single quoted' but not from text is 'partly single quoted'. Example 2: In abc 'foo bar' another' baz, no quote should be removed because the one on the beginning of the string is missing.

Here my code:

use strict;
use warnings;

my @names = ("'text is single quoted'", "text is 'partly single quoted'");
map {$_=~ s/^'|'$//g} @names;
print $names[0] . "\n" . $names[1] . "\n";

The or (|) in the regex ^'|'$ obviously also removes the second quote from the second string, which is not desired. I thought ^''$ would mean that it only matches if the first and the last character is a single quote, but this won't remove any single quote rom neither string.


Solution

  • You could use capturing group.

    s/^'(.*)'$/$1/
    

    ^ asserts that we are at the start and $ asserts that we are at the end of a line. .* greedily matches any character zero or more times.

    Code:

    use strict;
    use warnings;
    
    my @names = ("'text is single quoted'", "text is 'partly single quoted'");
    s/^'(.*)'$/$1/ for @names;
    
    print $names[0], "\n", $names[1], "\n";
    

    Output:

    text is single quoted
    text is 'partly single quoted'