UPDATED VERSION
Sorry for posting a second answer, but I just want to ascertain that you get notified of this answer.
This is the code for the file:
File file = new File("FilePath");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String t = "";
while((t = br.readLine()) != null)
{
str = str + t + "\n";
}
This is the regex:
Pattern p = Pattern.compile(".*\\s+(.+\\(.*?\\))\\s*\\{(.*"+keyword+"[^\\w*].*)\\}.*\\}$", Pattern.DOTALL);
Matcher m = p.matcher(str);
boolean notFound = true;
while(m.find())
{
System.out.println("Scope of keyword: " + m.group(1));
notFound = false;
}
if(notFound)
{
System.out.println("NOT FOUND");
}
Since you wanted the scope of the keyword, it is the nearest brace brackets within which it is declared, so I have assumed you have written its data type and the variable name in the keyword
. I'll see if I can handle more exceptions later :)
.*\\s+
- Takes in everything until the method name
(.+\\(.*?\\))\\s*\\{
- Stores the method name and parameters (In case there are overloaded methods)
(.*"+keyword+"
- Finds if the keyword is present after some other code
[^\\w*]
Ensures that the keyword exists by itself (Otherwise if the keyword is double x
, and double xy
is present, then it would be a match)
.*)\\}.*\\}$
- Sees if there are two Braces after the keyword is found (one to end the method or block [in case of if, else if, switch etc.], one to end the class)