Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"

like image 834
Jimmy22 Avatar asked May 18 '26 16:05

Jimmy22


1 Answers

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.

like image 191
Sergey Kalinichenko Avatar answered May 21 '26 06:05

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!