2015-03-24 76 views
0

我正在使用Java实现词法分析器。 Inside“String palavras_reservadas”我有所有保留字不能用来命名变量和类似的东西。匹配器负责在我的输入代码中查找这些保留字。 我把我输入代码中的所有行放在一个名为“vetor1”的ArrayList的不同位置。 我想在找到一个保留字时拆分这个“vetor1”。例如,我有这样的代码为我输入:在Java中使用分割

a = b + c; 
if (a > b) 
c = c + b; 

我的代码就会把每一行的阵列的不同位置:

v[0] = a = b + c; 
v[1] = if (a > b) 
v[2] = c = c + b; 

我想要做的是:

v[0] = a = b + c; 
v[1] = if 
v[2] = (a > b) 
v[3] = c = c + b; 

(或类似的东西)。我可以使用split来做到这一点吗?

这是我到目前为止有:

public class AnalisadorLexico { 
    public static void main(String args[]) throws FileNotFoundException { 

     List<String> vetor1 = new ArrayList<String>(); 
     File text = new File("/Users/Mvaguimaraes/Desktop/codigo.marcos"); 
     Scanner scnr = new Scanner(text); 

     String palavras_reservadas = "fim-se|enquanto|então|se|senão|para|de|até|faça|fim-para|fim-enquanto"; 
     Pattern r = Pattern.compile(palavras_reservadas); 
     int i = 0; 
      while(scnr.hasNextLine()) 
      { 

       String line = scnr.nextLine(); 
       vetor1.add(line); 
       Matcher m = r.matcher(scnr.nextLine()); 
       if (m.find()) { 
        System.out.println("Found value: " + m.group()); 

       } 

      } 

       for(i = 0; i<vetor1.size(); i++) 
       { 
         String value = vetor1.get(i); 
         System.out.println(value); 
       } 


     } 
} 

回答

0

使用分割,你应该有一个char分裂序列,例如 “如果(A> B)!” 分裂( “!” ) 为您提供了“如果”和“(A> b)”,不大的话,那么恐怕

+0

是否有任何其他方法可以在不使用拆分的情况下执行此操作? – 2015-03-24 22:09:54

+0

你可以通过使用正则表达式或者string.substring(0,3).equals(“if”)来检查关键字(比如if),然后像下面这样用substring手动分割它们:假设你在列表中的位置是k你做list.set(k,string.substring(0,3))和list.add(k + 1,string.substring(3,string.length) – Dix 2015-03-24 22:15:41

+0

在“m.group()”我有字符串拆分序列。那么,如何使用它来在代码中分割vetor1? – 2015-03-24 22:52:09

0

我想你可以使用Pattern类,例如

Pattern p = Pattern.compile("(if) ([(].*[)])\n")); 
Matcher matcher = p.matcher("if (a>b)"); 
if (matcher.matches()) { 
    matcher.group(1); // "if" 
    matcher.group(2); // "(a>b)" 
} 

基本内容在每个括号对中可以通过组(k)方法捕获,其中k是从左侧开始的kith括号对。有关详细信息,请参阅:https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html