Add escapeRegExp function (#95)

This commit is contained in:
Francesca Guiducci
2017-10-22 13:09:40 +05:30
committed by Shekhar Gulati
parent da85915b8d
commit 9fb07aa1f8
2 changed files with 31 additions and 0 deletions
+5
View File
@@ -1442,6 +1442,11 @@ public abstract class Strman {
.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());
+26
View File
@@ -1212,4 +1212,30 @@ public class StrmanTests {
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\\]\\)"));
}
}