2016-05-01 4 views
0

今、私はファイルを読み込んで複数の正規表現パターンと比較するために文字列に行を格納していますが、最初のパターンのみを検出しているようですどちらも?以下 が、これはまた、私は(ボイド楽しさを検出するための正規表現をしようとしていますテストするために使用しています入力ファイルのコード文字列を使用して複数の正規表現パターンと比較する

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import java.util.Scanner; 
import java.io.File; 
import java.io.FileNotFoundException; 

public class Project3 
{ 

    public static void main(String[] args) throws FileNotFoundException 
    { 
     String i; 
     String typenumber = "(\\s*)(int|double|float) (\\w) (=) (\\d)(;)"; 
     String function = "(\\s*)(void|int|string) (\\w) \\(\\) "; 
     Pattern r = Pattern.compile(typenumber); 
     Pattern t = Pattern.compile(function); 
     String path = "input.txt"; 
     File file = new File(path); 
     Scanner scanner = new Scanner(file); 
     String string = scanner.nextLine(); 
     Matcher m = r.matcher(string); 
     Matcher n = t.matcher(string); 


     while (scanner.hasNextLine()) 
     { 
      if(m.find()) 
      { 
       if (string != null) 
      { 
        if (string.matches(typenumber)) 
       { 
        i = string; 
        System.out.println(i); 
        System.out.println(m.group(3) + " -> data type: " + m.group(2) + ";" + " scope: " + "value: " + m.group(5)); 
       } 
        if (string.matches(function)) 
       { 
        i = string; 
        System.out.println(i); 
        System.out.println(m.group(3) + " -> data type: " + m.group(2) + ";" + " scope: "); 
       } 

      } 
      } 

     } 
    } 
} 

int a = 1; 

void fun() { 

    char c; 

    printf("%c", c); 

} 

int main() { 

int a = 3; 

    fun(); 

} 

答えて

0

あなたの二つのパターン

ですTYPE IDENTIFIER = NUM​​BER;

タイプ識別子()

は1つの

タイプ識別子に統合することができます(= NUM​​BER; | ()

これを試してみてください。

Pattern pat = Pattern.compile("(void|int|string)\\s+(\\w+)\\s*(=\\s*(\\d+)\\s*|\\(\\s*\\))"); 
File file = new File("input.txt"); 
try (Scanner in = new Scanner(file)) { 
    while (in.hasNextLine()) { 
     String i = in.nextLine(); 
     Matcher m = pat.matcher(i); 
     while (m.find()) { 
      System.out.println(i); 
      if (m.group(4) != null) 
       System.out.println(m.group(2) + " -> data type: " + m.group(1) + ";" + " scope: " + "value: " + m.group(4)); 
      else 
       System.out.println(m.group(2) + " -> data type: " + m.group(1) + ";" + " scope: "); 
     } 
    } 
} 
+0

あなたは、ああ、私は正規表現であることを置くことについては行くだろうか「}」のシンボルを検出するために望んでいる場合、あなたに感謝し、あなたのパターンがそれに失われた少し –

+0

イム私に説明することができますか?変数のスコープを決定するために}シンボルを検出しようとしているからです –

関連する問題