简体   繁体   中英

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.

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

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, eg:

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

but not the "T" in:

  • .This.
  • .AT.
  • .1T2.
  • .T3
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....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM