I am trying to learn regular expressions and the code below replaces every other whitespace with an underscore but I am trying to replace every third white space.
String replace = deletedWords.replaceAll("(?<!\\G\\w+)\\s","_");
Ex. output I get: "I have_been stuck_on this_problem forever"
Ex. output I want: "I have been_stuck on this_problem forever"
You can use the "last match or beginning of line" trick in a positive look-behind:
String s = "I have been stuck on this problem forever quick brown fox jumps over";
String r = s.replaceAll("(?<=(^|\\G)\\S{0,100}\\s\\S{0,100}\\s\\S{0,100})\\s", "_");
System.out.println(r);
The unfortunate consequence of using a look-behind is that you need to provide a max length for the match. I used {0,100} in place of * and {1,100} in place of +. You can use other limits if you prefer.
Demo.
Note: A workaround exists for the fixed limit. See this demo by hwnd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With