perl 正则表达式从字符串中删除引号

perl regex remove quotes from string

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

示例:我想删除 '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 (|) 显然也会从第二个字符串中删除第二个引号,这是不需要的。 我认为 ^''$ 意味着它仅在第一个 最后一个字符是单引号时才匹配,但这不会从两个字符串中删除任何单引号。

你可以使用 capturing group.

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

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

代码:

use strict;
use warnings;

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

print $names[0], "\n", $names[1], "\n";

输出:

text is single quoted
text is 'partly single quoted'

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

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

理由是:"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)"...

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

完整代码应该是:

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

print join "\n", @names;

输出:

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