Kaan Burak Sener Kaan Burak Sener -4 years ago 121
Java Question

Regex match for object creation in Java

I am searching the body of the constructor(s) of classes to find out any composition association between classes. So I have decided to use the following regex to perform this matching:

String regex = "(" + "^[this.]" + attribute.getName() + "=" + "|" + "^[this.]" + attribute.getName() + " =" + "|" + "^" + attribute.getName() + "=" + "|" + "^" + attribute.getName() + "=" + ")";


A class member might be initialized in the constructor in the following formats:

this.objectName =...; (with empty space)
this.objectName=...; (without empty space)
objectName =...; (with empty space)
objectName=...; (without empty space)


However, my regex still doesn't work as I expected.

Let's assume that I have initialized Student student; in the following constructor:

public Submission(long studentID, Date dateSubmitted, float grade){
this.studentID = studentID;
this.student= new Student();
this.grade = grade;
this.dateSubmitted = dateSubmitted;
}


And my regex should be dynamically created as:

String regex = "( ^[this.]student= | ^[this.]student = | ^student= | ^student = )";


if we assume that body is the content of the Submission(..) constructor

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(body);

if(m.find()) { ((ClassStructure)abstractStructure).addAssociation(AssociationType.COMPOSITION, node.getName());
isFound = true;
}


isFound should be initialized as true at the end of the compilation. In fact, it is not.

Could you please tell me how should I re-write the regex?

Answer Source

Since you are searching for this keyword in the beginning of the line, you don't get the desired results. Try to change your regex with this;

String regexTwo = "( (?:this\.)?" + attribute.getName() + "= | " + "(?:this\.)?" + attribute.getName() + " = )";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download