Bohemian
Bohemian

Reputation: 425098

How to replace all whitespace at the start of lines with a tab?

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.

Upvotes: 2

Views: 150

Answers (1)

Bohemian
Bohemian

Reputation: 425098

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.

Upvotes: 5

Related Questions