I'm new to using Regex and was wondering if someone could point me in the right direction.
My problem is as follows:
I need to pattern match an entire file to determine if code meets a rule. Local Variable Could Be Final. Essentially if the following code is within a file, I will need to check if the variable is assigned again. If not generate a warning to suggest an improvement.
public class Bar {
public void foo () {
String txtA = "a"; // if txtA will not be assigned again it is better to do this:
final String txtB = "b";
}
}
I of course have to do this for many other examples but I've not been taught Regex and it's not part of my course, if you can suggest a pattern for this or provide a link to help me learn, I'd very much appreciate it.
Ideally I'd like to do this in one go, I could of course generate a set of variable occurrences and "scan" the file again to see if these appear < 2 times. But Regex is lightning fast, and I want to approach this in such a way that I can have one method and I'll simply pass in the pattern + string for matching.
I've had a go already and I can find multiple occurrences but if another variable is between two instances my Regex won't pick them up..
It's close, but I feel will not work in pretty much every scenario bar one.
Regex: (\s*txtA\s*=\s*.*){2,}
public class Bar {
public void foo () {
String txtA = "a"; // matches
txtA = "ab"; // matches
String txtB = "xxx"; // breaks the match
txtA = "abc"; // doesn't match, but should.
}
}
If the above is the wrong way to approach this and you're aware of a more efficient way, perhaps some PHP Library, please do suggest.