From 025b3ddb3052c10e886d482b0234c68dec2b1a09 Mon Sep 17 00:00:00 2001 From: Francesca Guiducci Date: Sun, 15 Oct 2017 22:09:51 -0700 Subject: [PATCH] Add escapeRegExp function --- src/main/java/strman/Strman.java | 5 +++++ src/test/java/strman/StrmanTests.java | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/main/java/strman/Strman.java b/src/main/java/strman/Strman.java index 6598b0b..bb57787 100644 --- a/src/main/java/strman/Strman.java +++ b/src/main/java/strman/Strman.java @@ -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 predicate, final Supplier supplier) { if (predicate.test(value)) { throw new IllegalArgumentException(supplier.get()); diff --git a/src/test/java/strman/StrmanTests.java b/src/test/java/strman/StrmanTests.java index ae7b88e..cdf4bd2 100644 --- a/src/test/java/strman/StrmanTests.java +++ b/src/test/java/strman/StrmanTests.java @@ -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\\]\\)")); + } }