I have a method for a class that uses "java.util.regex.Pattern" and "java.util.regex.Matcher" to do regular expressions. I want to only have to compile my regular expressions once, so I have been creating static variables like this: (this is just a boiled down example, not my real code)
The problem I have with this is the actual regular expression is not close to where it is used an so it is not really clear what I am trying to find. In the code above it is not too bad, but in some methods I have 30+ regular expressions and it is a mess. What is a better way to do this to make it more clear what I am trying to match? I wish I could do something like this:
Or if there was native support of regex like in perl that would be much cooler, but I dought that will ever happen.
It sounds like you want to compile the pattern only once, but you want to have that pattern specified in a method. How about this:
This is an example of "lazy instantiation". If "checkStuff()" is never called, the pattern is never compiled. If it is called, the pattern compilation only happens the first time in. If this doesn't address your concern, please supply additional information and re-post. [ January 13, 2004: Message edited by: Wayne L Johnson ]
Originally posted by Kevin Fletcher: What is a better way to do this to make it more clear what I am trying to match?
Wayne's suggestion is good. Another one, which I hope you're already following, is to give the static variables better names than "mypattern" -- the name should describe what's being matched. FILENAME, IDENTIFIER, SSN, etc, would all be good names for these variables.
This is definitely better, Thank you. If I could just get rid of the class wide static variable somehow, it would be perfect. I tried doing this by creating a static variable inside an inner class inside of the method, but I keep getting a compiler complaint that inner classes can't have static declarations. Is there any way around that?