2

Is there a simple way to replace all whitespace at the start of lines with a single tab character?

I thought of using a loop and a StringBuffer:

String s = "some multi line text\n      foo bar\n   blah";
StringBuffer sb = new StringBuffer(s);
for (int i = 0; i < sb.length(); i++) {
    if (sb.charAt(i) == '\n') {
        while (sb.charAt(i + 1) == ' ')
            sb.delete(i + 1, i + 2);
        sb.insert(i + 1, '\t');
    }
}
s = sb.toString();

but that seems way too hard.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 2
    Still hunting for hats :P ? Questions like these shouldn't have exceptions to SO standards `Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions`. Next time, please make it a "model" for all users. Also putting some explanation in your answer is "appreciated". I mean not everyone knows that `(?m)` is an inline modifier :) – HamZa Dec 31 '13 at 15:42
  • 1
    @HamZa Am I *that* transparent? :) OK - code added. – Bohemian Dec 31 '13 at 16:02

1 Answers1

5

This should work:

str = str.replaceAll("(?m)^\\s+", "\t");

The (?m) flag means "carat and dollar match start and end of lines", so ^ will match the start of every line within the string.

Bohemian
  • 412,405
  • 93
  • 575
  • 722