0

我想从字符串中删除尾随和前导单引号,但如果引号从字符串中间开始,则不会。

示例:我想'text is single quoted'text is 'partly single quoted'. 示例 2:在abc 'foo bar' another' baz中,不应删除引号,因为缺少字符串开头的引号。

这是我的代码:

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";

|正则表达式中的 or ( )^'|'$显然也从第二个字符串中删除了第二个引号,这是不希望的。我认为^''$这意味着它仅在第一个最后一个字符是单引号时才匹配,但这不会删除任何单引号或字符串。

4

2 回答 2

4

您可以使用捕获组

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

^断言我们在开头并$断言我们在一行的结尾。.*贪婪地匹配任何字符零次或多次。

代码:

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";

输出:

text is single quoted
text is 'partly single quoted'
于 2015-01-09T14:33:23.603 回答
1

你试过这个正则表达式吗?

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

理由是:“用单引号替换任何字符串开头和结尾,并且不包含单引号,字符串本身(不包括开头和结尾引号)”......

你可以在这里测试它:regex101.com

完整的代码应该是:

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

print join "\n", @names;

哪个输出:

$ perl test.pl
text is single quoted
text is 'partly single quoted'
于 2015-01-09T14:33:36.183 回答