2016-05-01 37 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;

TYPE IDENTIFIER()

可以集成到一个

TYPE IDENTIFIER= 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

啊谢谢了,如果我想检测“}”符号如何将我去把在正则表达式?因为我试图检测}符号来确定变量的范围 –

相关问题