sp_user123
sp_user123

Reputation: 502

string.replaceAll to replace occurrences

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.

Upvotes: 4

Views: 220

Answers (3)

Vineet Singla
Vineet Singla

Reputation: 1677

String input = "abc.T.T.AT.T";
        StringTokenizer st = new StringTokenizer(input,".");
        StringBuffer sb = new StringBuffer();
        while(st.hasMoreTokens()){
            String token = st.nextToken();
            if(token.equals("T")){
                token= token.replace("T", "TOT");
            }
            sb.append(token+".");
        }
            if(!(input.lastIndexOf(".")==input.length()-1))
            sb.deleteCharAt(sb.lastIndexOf("."));
        System.out.println(sb.toString());

Hope this is what you require....

Upvotes: 1

stema
stema

Reputation: 92986

You can use word boundaries for this task:

text.replaceAll("\\bT\\b", "TOT");

This will replace a "T" only if it is not preceded and not followed by another word character (means no other letter or digit before or ahead).

This will work for your example. But you should be aware, that this will match on all "T" with non word characters around. Replaced will be, e.g.:

  • .T.
  • %T%
  • ,T,
  • !T-

but not the "T" in:

  • .This.
  • .AT.
  • .1T2.
  • .T3

Upvotes: 3

Kent
Kent

Reputation: 195059

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

Upvotes: 8

Related Questions