mirror of
https://github.com/shekhargulati/strman-java.git
synced 2026-10-20 14:34:04 +00:00
Add escapeRegExp function (#95)
This commit is contained in:
committed by
Shekhar Gulati
parent
da85915b8d
commit
9fb07aa1f8
@@ -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());
|
||||
|
||||
@@ -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\\]\\)"));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user