Skip to content

Commit

Permalink
Fix overly cautious regexp for = UseStringReplace (#332)
Browse files Browse the repository at this point in the history
* Fix overly cautious

* Add missing semicolon

* Pass java SourceSpec into rewriteRun, and negative cases

* Use different class names for each source

---------

Co-authored-by: Tim te Beek <[email protected]>
  • Loading branch information
blipper and timtebeek authored Aug 21, 2024
1 parent 717fbb1 commit 5aaf59f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ private static class UseStringReplaceVisitor extends JavaVisitor<ExecutionContex

private static final MethodMatcher REPLACE_ALL = new MethodMatcher("java.lang.String replaceAll(..)");
private static final Pattern ESCAPED_CHARACTER = Pattern.compile("\\\\\\.");
private static final Pattern METACHARACTERS = Pattern.compile("[(\\[{\\\\^\\-=$!|\\]})?*+.]");
private static final Pattern METACHARACTERS = Pattern.compile("[(\\[{\\\\^\\-$!|\\]})?*+.]|\\?=|<=");
private static final Pattern CHARACTER_CLASSES = Pattern.compile("\\\\d|\\\\D|\\\\s|\\\\S|\\\\w|\\\\W");

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,46 @@ public String method2() {
)
);
}

@Test
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/330")
void equalsSignOnlyWhenSafeToReplace() {
//language=java
rewriteRun(
java(
"""
class A {
String foo(String bar) {
return bar.replaceAll("=","|");
}
}
""",
"""
class A {
String foo(String bar) {
return bar.replace("=","|");
}
}
"""
),
java(
"""
class B {
String foo(String bar) {
return bar.replaceAll("(?=x)", "#");
}
}
"""
),
java(
"""
class C {
String foo(String bar) {
return bar.replaceAll("(?<=x)", "#");
}
}
"""
)
);
}
}

0 comments on commit 5aaf59f

Please sign in to comment.