开发者

How can I match mixed whitespace and () in Perl?

How do I improve my Perl regex to handle the __DATA__ below?

开发者_如何学运维
my ($type, $value) =~ /<(\w+)\s+(.*?)\(\)>/;  

__DATA__
<dynamic DynamicVar>
<dynamic DynamicVar > # not need attache the blackspace to $value when return
<dynamic DynamicFun()>
<dynamic DynamicFun() > # not need attache the blackspace to $value when return

I want to return the $type and $value as this format <$type $value>.


Rather than worrying about the details of the contents, just match anything inside the brackets.

my($type, $value) = m{< (\w+) \s+ (.*?) \s* >}x;

.*? means to match anything non-greedy which means it will look for the first thing to match, rather than the longest. This means it won't pick up whitespace at the end, it will leave it to the \s*. It also means it won't be fooled by <foo bar> and then a >.


you have got your answer, but here's another way, with lesser regex.

while(<DATA>){
    chomp;
    s/[<>]//g;
    my ($type, $value) = split /\s+/ ;
    print "type: $type\n";
    print "value: $value\n";
}


Try this regular expression:

/<(\w+)\s+(.*?)(?:\s*\(\)\s*)?>/

But I would also replace .*? with something more specific. If you just expect word characters, you could also use \w+ here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜