openrewrite / openrewrite/rewrite-static-analysis
Recipe to avoid calling `Pattern.compile()` too many times
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 62
- Forks
- 112
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 40
Description
What problem are you trying to solve?
Efficiency.
It's a typical and suggested pattern to have Regular Expressions constructed as constants in classes. As opposed to calling Pattern.compile("SOMETHING") or similar over and over again.
What precondition(s) should be checked before applying this recipe?
The recipe should kick in only if the argument is a literal or maybe other hard-coded constant.
In some rare cases one can imagine constructing the regexp programmatically, then there's little chance for immediate optimization.
Describe the situation before applying the recipe
public class EmailValidator {
public static boolean isValidEmail(String email) {
Pattern pattern = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$");
return pattern.matcher(email).matches();
}
}
Describe the situation after applying the recipe
public class EmailValidator {
private static final Pattern EMAIL_PATTERN =
Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$");
public static boolean isValidEmail(String email) {
return EMAIL_PATTERN.matcher(email).matches();
}
}
Context
- as far as I recall, there are other methods for constructing regular expressions in Java, they should be covered too
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by searching the repository for existing Java static-analysis recipe implementations and their tests, then compare how Pattern.compile() calls are handled. Done means a recipe recognizes literal or hard-coded regular expressions, moves reusable patterns to a constant as shown, and covers other mentioned Java regular-expression construction methods where appropriate.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100