0
votes

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.

2
What about this string: "abc 'foo bar' another' baz" - anubhava
No quote should be removed from that. - user1981275
But there are 3 single quotes in that string - anubhava
I think you should add more test cases to account for edge cases. - TLP
What about: ($result = $text) =~ s/[']//mg; - Andie2302

2 Answers

4
votes

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'
1
votes

Did you try this regexp?

/^'([^']*)'$/$1/

The rationale is: "substitute a any string starting and ending with a single quote, and that does not contain a single quote, with the string itself (starting and ending quotes excluded)"...

You can test it here: regex101.com

Full code should be:

my @names = ("'text is single quoted'", "text is 'partly single quoted'");
s/^'([^']*)'$/$1/ for @names;

print join "\n", @names;

Which outputs:

$ perl test.pl
text is single quoted
text is 'partly single quoted'