user1981275
user1981275

Reputation: 13372

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.

Upvotes: 0

Views: 5507

Answers (2)

MarcoS
MarcoS

Reputation: 17711

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'

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

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'

Upvotes: 4

Related Questions