我有以下文字:
some cool color #12eedd more cool colors #4567aa
我希望这个字符串将被转换为:
some cool color #{1} more cool colors #{2}
用Java(1.6)怎么可能做到这一点?
到目前为止我发现的是颜色的正则表达式:#[0-9abcdef]{3,6}
您可以使用appendReplacement
和appendTail
来自 Matcher 类
String data = "some cool color #12eedd more cool colors #4567aa";
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("#[0-9a-f]{3,6}", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(data);
int i = 1;
while (m.find()) {
m.appendReplacement(sb, "#{" + i++ + "}");
}
m.appendTail(sb);//in case there is some text left after last match
String replaced = sb.toString();
System.out.println(replaced);
输出:
some cool color #{1} more cool colors #{2}
您可以尝试不使用正则表达式
String str="some cool color #12eedd more cool colors #4567aa";
StringBuilder sb=new StringBuilder();
String[] arr=str.split(" ");
int count=1;
for(String i:arr){
if(i.charAt(0)=='#'){
sb.append("#{"+count+"} ");
count++;
}
else {
sb.append(i+" ");
}
}
System.out.println(sb.toString());
输出:
some cool color #{1} more cool colors #{2}
好吧,这可能不是您正在寻找的,但您有其他选择而不使用正则表达式,这很简单,有点肤色:)
StringBuilder q = new StringBuilder("some cool color #12eedd more cool colors #4567aa");
int i;
int j=1;
while(q.indexOf("#")>0){
q.replace(i=q.indexOf("#"),i+7, "${"+ j++ +"}");
}
String result = q.toString().replaceAll("\\$", "#");
System.out.println(result);
输出:
some cool color #{1} more cool colors #{2}