Emre Ozuslu
Emre Ozuslu

Reputation: 1

Java RegEx to find method names

I want to find methods and parametres names with RegEx in Java. I have a C file and I read this file. My Regex part can find method of names but additional, it finds other names such as printf, scanf... I need just names of methods.

public class Deneme {


public static void main(String[] args) throws FileNotFoundException, IOException {

    try{
        File f=new File("C:\\Users\\Emre\\Documents\\NetBeansProjects\\deneme\\src\\deneme\\Program.c"); //Open a file
        String s;
        FileReader reader=new FileReader(f); 
        BufferedReader br=new BufferedReader(reader); //Read file
        while((s=br.readLine())!=null){
            String regex="(?!\\bif\\b|\\bfor\\b|\\bwhile\\b|\\bswitch\\b|\\btry\\b|\\bcatch\\b)(\\b[\\w]+\\b)[\\s\\n\\r]*(?=\\(.*\\))";
            Pattern funcPattern = Pattern.compile(regex);
            Matcher m = funcPattern.matcher(s); //Matcher is used to match pattern with string 
            if(m.find()){
                System.out.println(m.group(0));
            }
        }
    }


    catch(Exception e){
            e.printStackTrace();
    }
}

}

This is my C file

#include "stdio.h" 
#include "stdlib.h" 

void DiziYazdir(int *p,int uzunluk)
{   
int i=0;  
for(;i<uzunluk;i++) 
printf("%d ",p[i]); 
} 

int DiziTopla(int *p,int uzunluk)
{ 
int i=0;  int toplam=0;  
for(;i<uzunluk;i++) 
toplam += p[i];  
return toplam; 
}

int main()
{ 
int x,y;  
printf("x:");  
scanf("%d",&x);  
printf("y:");  
scanf("%d",&y);  
int sonuc = x + y;  
printf("Sonuc:%d\n\n",sonuc);  
int *dizi = malloc(3*sizeof(int));  
dizi[0]=x;  
dizi[1]=y;  
dizi[2]=sonuc;  
DiziYazdir(dizi,3);  
printf("\n\nToplam Deger:%d",DiziTopla(dizi,3));  
free(dizi);  
return 0; 
}

There are lots of methods and I cannot write all the methods in "String regex" like "\bfor\b|\bwhile\b". Is there any RegEx method to fix that ? or Is there a RegEx method that covers the whole? It will just print names of method and parameters such as DiziYazdir, DiziTopla, Main and for methods *p, int uzunluk.

Upvotes: 0

Views: 107

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51891

The following reg ex should work fine, one word starting the line followed by space and another word (letters and digits) and then any character sequence inside a pair of parantheses followed by possibly a space and then a {

^\w*\s+[\w\d]+\(.*\)\s?\{?

as a java string I guess it should be

String pattern = "^\\w*\\s+[\\w\\d]+\\(.*\\)\s?\\{?";

Upvotes: 1

Related Questions