如何使用 perl 正则表达式来解析 java 文件



我想了解更多关于在perl中使用正则表达式来解析文本的信息,方法是解析一个简单的.java文件,从中找出所有的int,boolean,double和string变量(没有数组(,并将这些变量放入它们各自的perl数组中。例如,如果.java文件中有一个名为"x"的 int 变量,则 perl 会将字符串 'x' 插入到包含所有 int 变量的数组中,依此类推,用于双精度、布尔值和字符串。虽然我可以在perl中打开文件并进行基本的paping,例如将文本行打印到终端,但不幸的是,我真的不知道如何做任何更复杂的事情,这将涉及使用正则表达式

以下是我到目前为止在我的perl脚本中写下的内容:

use strict;
use warnings;
print "enter the name of the java file you want to parse:n";
my $javafile = <STDIN>;
chomp $javafile;
my @listofdubs=();
my @listofints=();
my @listofbools=();
my @listofstrings=();
open my $info, $javafile or die "Could not open $javafile: $!";
while( my $line = <$info>)  {   
#print "$linen"; 
}
close $info;

这是我制作的一个简单的java文件,里面有一些int,boolean,double和string变量:

public class examplejava{
public static void main(String[] args) {
System.out.println("Hello, World");
int thing= 70;
int boo = 31;
boolean example3= false;
String example1= "stack";
String example2= "overflow";
double example6= 4.32;
boolean example4= true;
double example5= 2.4349;
}
}

虽然这在一般情况下可能非常困难,但对示例数据执行一些操作非常简单:

#!/usr/bin/perl
use strict;
use warnings;
my @listofdubs    = ();
my @listofints    = ();
my @listofbools   = ();
my @listofstrings = ();
while (<>) {
push @listofdubs,    $1 if /bdoubles+(w+)/;
push @listofints,    $1 if /bints+(w+)/;
push @listofbools,   $1 if /bbooleans+(w+)/;
push @listofstrings, $1 if /bStrings+(w+)/;
}
print "@listofdubsn";

(我已经删除了所有用户提示的内容。相反,这接受文件名作为命令行参数。

最新更新