[英]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将所有单个
T
替换为TOT
的字符串,例如
"abc.TOT.TOT.AT.TOT"
strings.replaceAll
not working for this. strings.replaceAll
不适用于此。
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).仅当“T”之前和之后都没有另一个单词字符(意味着之前或之前没有其他字母或数字)时,才会替换“T”。
This will work for your example.这将适用于您的示例。 But you should be aware, that this will match on all "T" with non word characters around.
但是您应该知道,这将匹配所有带有非单词字符的“T”。 Replaced will be, eg:
替换将是,例如:
but not the "T" in:但不是“T”:
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....希望这是你所需要的......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.