Skip to content

Commit

Permalink
Add escapeRegExp function
Browse files Browse the repository at this point in the history
  • Loading branch information
Francesca Guiducci committed Oct 16, 2017
1 parent 7b552eb commit 025b3dd
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/main/java/strman/Strman.java
Original file line number Diff line number Diff line change
Expand Up @@ -1404,6 +1404,11 @@ public static String[] chop(String input, int step) {
.toArray(String[]::new);
}

public static String escapeRegExp(final String input) {
validate(input, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return input.replaceAll("[\\\\\\^\\$\\*\\+\\-\\?\\.\\|\\(\\)\\{\\}\\[\\]]", "\\\\$0");
}

private static void validate(String value, Predicate<String> predicate, final Supplier<String> supplier) {
if (predicate.test(value)) {
throw new IllegalArgumentException(supplier.get());
Expand Down
26 changes: 26 additions & 0 deletions src/test/java/strman/StrmanTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -1186,4 +1186,30 @@ public void chop_shouldChopStringByStep() throws Exception {
assertThat(chop("whitespace", 3).length, equalTo(4));
assertThat(chop("whitespace", 0)[0].length(), equalTo(10));
}

@Test(expected = IllegalArgumentException.class)
public void escapeRegExp_shouldThrowException() throws Exception {
escapeRegExp(null);
}

@Test
public void escapeRegExp_shouldEscapeRegExp() throws Exception {
assertThat(escapeRegExp("\\"), equalTo("\\\\"));
assertThat(escapeRegExp("^"), equalTo("\\^"));
assertThat(escapeRegExp("$"), equalTo("\\$"));
assertThat(escapeRegExp("*"), equalTo("\\*"));
assertThat(escapeRegExp("+"), equalTo("\\+"));
assertThat(escapeRegExp("-"), equalTo("\\-"));
assertThat(escapeRegExp("?"), equalTo("\\?"));
assertThat(escapeRegExp("."), equalTo("\\."));
assertThat(escapeRegExp("|"), equalTo("\\|"));
assertThat(escapeRegExp("("), equalTo("\\("));
assertThat(escapeRegExp(")"), equalTo("\\)"));
assertThat(escapeRegExp("{"), equalTo("\\{"));
assertThat(escapeRegExp("}"), equalTo("\\}"));
assertThat(escapeRegExp("["), equalTo("\\["));
assertThat(escapeRegExp("]"), equalTo("\\]"));
assertThat(escapeRegExp("How much is (2+3)? 5"), equalTo("How much is \\(2\\+3\\)\\? 5"));
assertThat(escapeRegExp("\\s|_|-|(?<=[a-z])(?=[A-Z])"), equalTo("\\\\s\\|_\\|\\-\\|\\(\\?<=\\[a\\-z\\]\\)\\(\\?=\\[A\\-Z\\]\\)"));
}
}

0 comments on commit 025b3dd

Please sign in to comment.