2015-03-24 75 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