문제

How do I match the following strings using a 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";

i.e match 0 or n number of function qualifiers separated by atleast one space followed by string "function".

It shouldn't match

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

Is there something similar to

$line=~/^([evp\s]*) function/ ;

which can be used for words instead of characters ?

도움이 되었습니까?

해결책

(?:PAT1|PAT2) is to patterns as [ab] is to chars.

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

다른 팁

I came up with a solution that looks a lot like ikegami's:

#!/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";
    }
}

Which produces:

$ 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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top