将文本与给定字符匹配,但在Perl中将单个引号中的字符出现排除在外

时间:2014-04-03 23:10:20

标签: regex perl

我正在尝试从字符串中提取文本直到下一次出现/,不计算单引号内出现的斜杠。例如

my $str="test 'a/b' c/ xxx /";
$str =~ /(.*?)\//;
print "$1\n";

给出

test 'a

虽然我想得到:

test 'a/b' c

4 个答案:

答案 0 :(得分:4)

你可以试试这个:

$str =~ /^((?>[^'\/]+|'[^']*')*)\//;

答案 1 :(得分:4)

Text::ParseWords可以处理引用的分隔符:

use strict;
use warnings;
use Text::ParseWords;

my $str = "test 'a/b' c/ xxx /";
my ($first) = quotewords('/', 1, $str);
print $first;

<强>输出:

test 'a/b' c

答案 2 :(得分:3)

my $str="test 'a/b' c/ xxx /";

$str =~ m{^((?>[^'/]+|'[^']*')*)/};

print $1;

或者,如果字符串可以包含转义的单引号:

$str =~ m{^((?>[^'/]+|'(?>[^'\\]+|\\.)*')*)/}x;

答案 3 :(得分:0)

如果你的字符串数据总是&#34; A / B /&#34;然后你可以使用以下内容:

#!/usr/bin/perl -w

my $str = "test 'a/b' c/ xxx /";
$str =~ m/(.*)\/(.*)\/$/;
print "$1\n";