Java replace every Nth specific character (like space) to String

I am trying to learn regex and the code below replaces all other spaces with an underscore, but I am trying to replace every third space.

 String replace = deletedWords.replaceAll("(?<!\\G\\w+)\\s","_");

      

Ex. I get: "I'm forever stuck with this_problem"

Ex. the output I want is: "I'm forever on this_problem"

+3


source to share


2 answers


You can use the "last match or start of line" trick in a positive way:

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);

      

An unfortunate consequence of using look and feel is that you need to provide the maximum length to match. Instead, +

I used {0,100}

instead of *

and {1,100}

. You can use other restrictions if you like.



Demo version

Note. A workaround exists for a fixed limit. See this hwnd demo .

+3


source


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);

      

There is no need to check for adjacency, since the string is parsed from left to right and because characters are consumed (including the first two spaces), so the position of the latter is \\s+

always a multiple of 3.



A more general pattern for the nth character:

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

      

+2


source







All Articles