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:
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.