4

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
sp_user123
  • 512
  • 3
  • 6
  • 28

3 Answers3

8

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
Kent
  • 189,393
  • 32
  • 233
  • 301
  • just out of curiosity, what happens when the string has something like this:- `.(space)T(space)(space).`? – Rahul Apr 29 '13 at 11:23
  • 3
    then the replace statement won't work. It is just based on OP's example. "dot" separated. well sure he didn't mention the definition of `single T`. at least my codes should work for his example. – Kent Apr 29 '13 at 11:26
  • An equivalent but super confusing regex is `(?<![^.])T(?![^.])` – nhahtdh Apr 29 '13 at 11:34
  • @nhahtdh You had a typo, I think you meant `(?<![^.])T(?![^.])` negative of negative...:D – Kent Apr 29 '13 at 11:37
  • @Kent: Fixed it momentarily before you posted the comment. (The problem was forgetting the look-behind's `<`). – nhahtdh Apr 29 '13 at 11:38
3

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
stema
  • 90,351
  • 20
  • 107
  • 135
  • 2
    No letter or digits **or underscore**. So `T` in `%T%` will be replaced. I don't say it is wrong, just for OP's information. – nhahtdh Apr 29 '13 at 11:37
  • @nhahtdh, thanks for your clarification. I added some examples to my answer. – stema Apr 29 '13 at 11:45
1
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....

Vineet Singla
  • 1,609
  • 2
  • 20
  • 34