Perl正则表达式匹配

时间:2013-07-15 20:01:56

标签: regex perl regex-group

如何使用perl regexp匹配以下字符串?

$line="virtual void function";
$line="virtual function";
$line="void function";
$line="function";
$line="pure virtual function";
$line="extern function";
$line="extern void function";

即匹配0或n个由至少一个空格分隔的函数限定符,后跟字符串“function”。

它不应该匹配

$line="// function";
$line="asdfgh";     
$line="endfunction";     

是否有与

相似的内容
$line=~/^([evp\s]*) function/ ;

可以用于单词而不是字符吗?

2 个答案:

答案 0 :(得分:2)

(?:PAT1|PAT2)是模式,[ab]是字符。

/^(?:(?:extern|pure|virtual|void)\s+)*function/

答案 1 :(得分:1)

我提出了一个看起来很像ikegami的解决方案:

#!/usr/bin/env perl
use strict;
use warnings;

my @lines = (
    "virtual void function",
    "virtual function",
    "void function",
    "function",
    "pure virtual function",
    "extern function",
    "extern void function",
    "// function",
    "asdfgh",
    "endfunction",
);

foreach my $line (@lines) {
    if ($line =~ m{^((virtual|void|pure|extern)\s+)*function}) {
        print "$line is a " . ($1||"'plain function'") . "\n";
    }
    else {
        print "ignored: $line\n";
    }
}

产生:

$ perl 17662838-perl-regex-word-matching.pl
virtual void function is a void
virtual function is a virtual
void function is a void
function is a 'plain function'
pure virtual function is a virtual
extern function is a extern
extern void function is a void
ignored: // function
ignored: asdfgh
ignored: endfunction