-3

如何使用 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/ ;

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

4

2 回答 2

2

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

/^(?:(?:extern|pure|virtual|void)\s+)*function/
于 2013-07-15T21:03:27.800 回答
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
于 2013-07-15T22:17:21.777 回答