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 19, 2017
1 parent befff26 commit 0a7e352
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 @@ -1419,6 +1419,11 @@ public static String startCase(final String input) {
.map(w -> upperFirst(w.toLowerCase())).collect(joining(" "));
}

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 @@ -1204,4 +1204,30 @@ public void startCase_shouldStartCaseInputString() throws Exception {
assertThat(startCase("--dashes--"), equalTo("Dashes"));
assertThat(startCase("dashes----between----words"), equalTo("Dashes Between Words"));
}

@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 0a7e352

Please sign in to comment.