Perl regex word matching

Jean Source

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 ?

regexperlregex-group

Answers

answered 5 years ago ikegami #1

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

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

answered 5 years ago Chisel #2

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

comments powered by Disqus