Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.replaceAll to replace occurrences

Tags:

java

string

regex

I need to replace a string:

"abc.T.T.AT.T"

to a string with all single T to be replaced by TOT like

"abc.TOT.TOT.AT.TOT"

strings.replaceAll not working for this.

like image 579
sp_user123 Avatar asked Dec 16 '22 11:12

sp_user123


1 Answers

look around will solve your problem:

s.replaceAll("(?<=\\.|^)T(?=\\.|$)", "TOT");

if you do:

String s = "T.T.T.AT.T.fT.T.T";
System.out.println(s.replaceAll("(?<=\\.|^)T(?=\\.|$)", "TOT"));

output would be:

TOT.TOT.TOT.AT.TOT.fT.TOT.TOT
like image 200
Kent Avatar answered Jan 02 '23 15:01

Kent