TextUtils { @Nonnull public static String normalizeWhitespace(@Nonnull String source) { source = normalizeNewlines(source); Pattern pattern = Pattern.compile("((^[ \t]+)|([ \t]+$))", Pattern.MULTILINE); Matcher matcher = pattern.matcher(source); source = matcher.replaceAll(""); Pattern pattern2 = Pattern.compile("^\r?\n?", Pattern.MULTILINE); Matcher matcher2 = pattern2.matcher(source); source = matcher2.replaceAll(""); Pattern pattern3 = Pattern.compile("\r?\n?$"); Matcher matcher3 = pattern3.matcher(source); source = matcher3.replaceAll(""); source = normalizeNewlines(source, "\n"); return source; }  @Nonnull static String normalizeNewlines(@Nonnull String source); @Nonnull static String normalizeNewlines(@Nonnull String source, String newlineValue); @Nonnull static String normalizeWhitespace(@Nonnull String source); @Nonnull static String stripComments(@Nonnull String source);  }
@Test public void testNormalizeWhitespace() { Assert.assertEquals("", TextUtils.normalizeWhitespace(" ")); Assert.assertEquals("hello", TextUtils.normalizeWhitespace("hello ")); Assert.assertEquals("hello", TextUtils.normalizeWhitespace(" hello")); Assert.assertEquals("hello", TextUtils.normalizeWhitespace(" hello ")); Assert.assertEquals("hello\nworld", TextUtils.normalizeWhitespace("hello \n \n world")); }