I’m using java to try to replace the four spaces at the beginning of a new line to a tab. I would like to do this using regular expressions. My issue is that the regex is currently replacing all four-space-sequences with a single tab. I want it to insert a tab for each four-space-sequence. Right now I have:
public String translate(String text) {
text = text.replaceAll("(?m)^( )+", "\t");
return text;
}
You don’t want the
+because you want exactly 4 spaces, and you need a look-behind assertion:Note: This should only be used for input of about 10K or less due to the backtracking required by the look behind. For larger input, use a pattern and matcher etc
Unlike the other answers, this one actually works (see test below), because it uses a positive look-behind
(?<=^ *)to assert that only spaces are between the start of input and the target replacement, without which you’ll only match the first 4 spaces:Output: