Perl正则表达式找到关键字而不是变量

ana*_*ali 2 regex perl

我正在尝试创建一个正则表达式如下:

print $time . "\n"; - >仅匹配打印,因为时间是变量($ before)

$epoc = time(); - >只匹配时间

我现在的正则表达式是,/(?-xism:\b(print|time)\b)/g但它在第一个例子中的$ time时间匹配.

点击这里

我试过像[^\$]这样的东西但是它再打印不匹配了.

(我会有更多关键字,如print | time | ... | ...)

谢谢

Mil*_*ler 7

解析perl代码是一种常用且有用的教学工具,因为学生必须理解解析技术和他们试图解析的代码.

但是,要做到这一点,最好的建议是使用 PPI

以下脚本解析自身并输出所有的裸字.如果您愿意,可以将裸字列表与您尝试匹配的裸字列表进行比较.注意,这将避免字符串,注释等内容.

use strict;
use warnings;

use PPI;

#my $src = do {local $/; <DATA>};  # Could analyze the smaller code in __DATA__ instead
my $src = do {
    local @ARGV = $0;
    local $/;
    <>;
};

# Load a document
my $doc = PPI::Document->new( \$src );

# Find all the barewords within the doc
my $barewords = $doc->find( 'PPI::Token::Word' );
for (@$barewords) {
    print $_->content, "\n";
}

__DATA__
use strict;
use warnings;

my $time = time;

print $time . "\n";
Run Code Online (Sandbox Code Playgroud)

输出:

use
strict
use
warnings
use
PPI
my
do
local
local
my
PPI::Document
new
my
find
for
print
content
__DATA__
Run Code Online (Sandbox Code Playgroud)