How to replace the occurrence of the nth character in a string?
•
Java
I need to replace all commas after the fifth Therefore, if a string contains 10 commas, I want to leave only the first five and delete all subsequent commas
How can I do this?
String sentence = "Test,test,test"; String newSentence = sentence.replaceAll(",[6]","");
Solution
Just capture all the characters from the beginning to the fifth comma and use the alternating operator to match all the remaining commas Therefore, all remaining commas should be matched after | Replacing all matching characters with $1 will provide you with the required output
sentence.replaceAll("^((?:[^,]*,){5})|,","$1");
DEMO
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码