@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
private static final Pattern pattern = Pattern.compile("^\\s+\n|\\n\\s+\\n|\\n\\n|\\s+$"); private void removeBlankLines(SpannableStringBuilder sb) { Matcher matcher = pattern.matcher(sb); ArrayList<Pair<Integer, Integer>> matchList = new ArrayList<>(); while (matcher.find()) { matchList.add(new Pair<>(matcher.start(), matcher.end())); }
for (int i = matchList.size() - 1; i >= 0; i--) { int start = matchList.get(i).first; int end = matchList.get(i).second; sb.delete(start, end); sb.insert(start, "\n"); }
if (sb.length() > 0) { if (sb.charAt(0) == '\n') { sb.delete(0, 1); } } if (sb.length() > 0) { if (sb.charAt(sb.length() - 1) == '\n') { sb.delete(sb.length() - 1, sb.length()); } } }
@Test public void test() throws Exception { String[][] tests = { {" ", ""}, {" \n", ""}, {"1", "1"}, {"12", "12"}, {"1\n", "1"}, {"\n1", "1"}, {"\n\n1", "1"}, {"1\n\n", "1"}, {"\n \n1", "1"}, {"1\n \n", "1"}, {" 1\n \n", " 1"}, {"1 \n", "1"}, {"\n1\n", "1"}, {"\n\n1\n", "1"}, {" \n \n1\n", "1"}, {"1\n2", "1\n2"}, {"1\n2 ", "1\n2"}, {"1\n2 \n", "1\n2"}, {"1\n\n2", "1\n2"}, {"1\n\n\n2", "1\n2"}, {"1\n \n\n2", "1\n2"}, {"1\n \n \n2", "1\n2"}, {"1\n \n \n2\n 3 \n", "1\n2\n 3"}, {"1\n\n\n2\n\n\n\n3", "1\n2\n3"}, {"1\n\n\n2\n\n\n\n3\n \n4", "1\n2\n3\n4"}, {" \na", "a"}, {" \n \n \n \na", "a"}, {" \n \n \n \na", "a"}, {" a ", " a"}, {" a \nz", " a \nz"}, {" a \n\nk", " a \nk"}, {" a \n\n\nd\n\n", " a \nd"}, {" a \n\n\ne\n \n", " a \ne"}, {" a \n\n\nf \n \n", " a \nf"}, {" a \n\n\ng \n \n ", " a \ng"}, {" a \n\n\nb \n \n k", " a \nb \n k"}, }; for (String[] test : tests) { SpannableStringBuilder sb = new SpannableStringBuilder(test[0]); removeBlankLines(sb); assertEquals(test[1], sb.toString()); } } }