TextUtils { public static String sanitize(String s) { if(s == null || s.isEmpty()) { return s; } String clean = RegExUtils.removePattern(s,"^(?:\\s|\\p{Punct})+|(?:\\s|[\\p{Punct}&&[^.]])+$"); clean = clean.replaceAll("([^\\s&])\\&", "$1 &"); clean = clean.replaceAll("\\&([^\\s&])", "& $1"); clean = StringUtils.normalizeSpace(clean); return clean; }  static String sanitize(String s);  }
@Test public void testSanitize() { assertThat(TextUtils.sanitize(null)).isNull(); assertThat(TextUtils.sanitize("")).isEqualTo(""); assertThat(TextUtils.sanitize("abc")).isEqualTo("abc"); assertThat(TextUtils.sanitize("abc def")).isEqualTo("abc def"); assertThat(TextUtils.sanitize(" abc")).isEqualTo("abc"); assertThat(TextUtils.sanitize("abc ")).isEqualTo("abc"); assertThat(TextUtils.sanitize(" abc def ")).isEqualTo("abc def"); assertThat(TextUtils.sanitize(" abc def ")).isEqualTo("abc def"); assertThat(TextUtils.sanitize(", abc, def ,")).isEqualTo("abc, def"); assertThat(TextUtils.sanitize(" , abc, def ,")).isEqualTo("abc, def"); assertThat(TextUtils.sanitize(" ,.?!&^#$%@ abc-d & def ,?:+-")).isEqualTo("abc-d & def"); assertThat(TextUtils.sanitize("abc&def")).isEqualTo("abc & def"); assertThat(TextUtils.sanitize("abc && def")).isEqualTo("abc && def"); assertThat(TextUtils.sanitize("abc&&def")).isEqualTo("abc && def"); assertThat(TextUtils.sanitize("N.Y.")).isEqualTo("N.Y."); assertThat(TextUtils.sanitize("abc\tde\tf")).isEqualTo("abc de f"); }