Java replace every Nth specific character (e.g. space) in String

1.6k views Asked by At

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"

2

There are 2 answers

5
Sergey Kalinichenko On BEST ANSWER

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.

0
Casimir et Hippolyte On

You can use this:

String z = "I have been stuck on this problem forever quick brown fox jumps over";
String p = z.replaceAll("(\\s+\\S+\\s+\\S+)\\s+", "$1_");
System.out.println(p);

No need to test the contiguity since the string is parsed from left to right and because the characters (including the first two spaces) are consumed, so the position of the last \\s+ is always a multiple of 3.

A more general pattern for the nth character is:

((?:target all_that_is_not_the_target){n-1}) target