perl regex从字符串中删除引号

时间:2015-01-09 14:29:29

标签: regex string perl single-quotes

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

示例:我想从'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";

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

2 个答案:

答案 0 :(得分:4)

您可以使用capturing group

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'

答案 1 :(得分: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'