Regex to match only innermost delimited sequence

大憨熊 提交于 2019-12-01 10:31:53
@matches = $string =~ /(<<(?:(?!<<|>>).)*>>)/g;

(?:(?!PAT).)* is to patterns as [^CHAR]* is to characters.

$string = 'do not match this <<but match this>> not this <<BUT NOT THIS <<this too>> IT HAS CHILDREN>> <<and <also> this>>';
@matches = $string =~ /(<<(?:[^<>]+|<(?!<)|>(?!>))*>>)/g;

Here's a way to use split for the job:

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;

Keeps the tags in there, if you want them removed, just do:

@match = map { s/^<<//; s/>>$//; $_ } @match;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!