Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not rewrite String.replaceAll with special chars in replacement string #306

Merged
merged 3 commits into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/main/java/org/openrewrite/staticanalysis/UseStringReplace.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,21 @@ public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx)

//Checks if method invocation matches with String#replaceAll
if (REPLACE_ALL.matches(invocation)) {
Expression secondArgument = invocation.getArguments().get(1);

//Checks if the second argument is a string literal with $ or \ in it as this has special meaning and
// should not be rewritten:
//https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/util/regex/Matcher.html#replaceAll(java.lang.String)
if (isStringLiteral(secondArgument)) {
J.Literal literal = (J.Literal) secondArgument;
String value = (String) literal.getValue();

if (Objects.nonNull(value) && (value.contains("$") || value.contains("\\"))) {
// do not rewrite
return invocation;
}
}

Expression firstArgument = invocation.getArguments().get(0);

//Checks if the first argument is a String literal
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,4 +146,40 @@ public void method() {
)
);
}

@Test
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/301")
@DisplayName("String#replaceAll is not replaced by String#replace, because second argument has a backslash in it")
void replaceAllUnchangedIfBackslashInReplacementString() {
rewriteRun(
//language=java
java(
"""
class Test {
public String method() {
return "abc".replaceAll("b", "\\\\\\\\\\\\\\\\");
}
}
"""
)
);
}

@Test
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/301")
@DisplayName("String#replaceAll is not replaced by String#replace, because second argument has a dollar sign in it")
void replaceAllUnchangedIfDollarInReplacementString() {
rewriteRun(
//language=java
java(
"""
class Test {
public String method() {
return "abc".replaceAll("b", "$0");
}
}
"""
)
);
}
}