4

我有一个字符串,其中包含由多个字符分隔的序列:<<>>. 我需要一个正则表达式来只给我最里面的序列。我已经尝试过前瞻,但它们似乎并没有按照我期望的方式工作。

这是一个测试字符串:

'do not match this <<but match this>> not this <<BUT NOT THIS <<this too>> IT HAS CHILDREN>> <<and <also> this>>'

它应该返回:

but match this
this too
and <also> this

正如您在第三个结果中看到的那样,我不能只使用/<<[^>]+>>/,因为字符串可能有一个分隔符字符,但不是连续两个字符。

我刚从试错中解脱出来。在我看来,这不应该这么复杂。

4

3 回答 3

9
@matches = $string =~ /(<<(?:(?!<<|>>).)*>>)/g;

(?:(?!PAT).)*是模式,[^CHAR]*也是字符。

于 2011-08-09T12:36:52.257 回答
6
$string = 'do not match this <<but match this>> not this <<BUT NOT THIS <<this too>> IT HAS CHILDREN>> <<and <also> this>>';
@matches = $string =~ /(<<(?:[^<>]+|<(?!<)|>(?!>))*>>)/g;
于 2011-08-09T03:10:06.977 回答
0

这是一种split用于这项工作的方法:

my $str = 'do not match this <<but match this>> not this <<BUT NOT THIS <<this too>> IT HAS CHILDREN>> <<and <also> this>>';
my @a = split /(?=<<)/, $str;
@a = map { split /(?<=>>)/, $_ } @a;

my @match = grep { /^<<.*?>>$/ } @a;

将标签保留在那里,如果您想删除它们,只需执行以下操作:

@match = map { s/^<<//; s/>>$//; $_ } @match;
于 2011-08-09T13:06:11.663 回答