Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the n th occurance of a character in a String ?

Tags:

java

regex

I need to replace all commas after the 5th one. So if a String contains 10 commans, I want to leave only the first 5, and remove all subsequent commas.

How can I do this ?

String sentence = "Test,test,test,test,test,test,test,test"; 
String newSentence = sentence.replaceAll(",[6]",""); 
like image 361
Emily Avatar asked Dec 03 '25 22:12

Emily


1 Answers

Just capture all the characters from the start upto the 5th comma and match all the remaining commas using the alternation operator |. So , after | should match all the remaining commas. By replacing all the matched chars with $1 will give you the desired output.

sentence.replaceAll("^((?:[^,]*,){5})|,", "$1");

DEMO

like image 100
Avinash Raj Avatar answered Dec 05 '25 11:12

Avinash Raj



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!