简体   繁体   English

如何使用Java中的正则表达式用字符串中的连续数字替换某些子字符串?

[英]How to replace some substrings with consequitve numbers in a string using regular expression in java?

I have the following text: 我有以下文字:

some cool color #12eedd more cool colors #4567aa

I want that this string will be transformed to: 我希望该字符串将被转换为:

some cool color #{1} more cool colors #{2}

How is it possible to do it in Java (1.6)? 用Java(1.6)如何做到?

What I've found so far is the regex for color: #[0-9abcdef]{3,6} 到目前为止,我发现的是颜色的正则表达式: #[0-9abcdef]{3,6}

You can use appendReplacement and appendTail from Matcher class 您可以使用Matcher类中的appendReplacementappendTail

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);

output: 输出:

some cool color #{1} more cool colors #{2}

You can try without regex as this 您可以尝试不使用正则表达式

    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());

out put: 输出:

 some cool color #{1} more cool colors #{2}

Well may be this is not you are looking for but you have other option without using regex, this is simple with little bit complexion :) 好吧,可能这不是您要查找的,但是您无需使用正则表达式就拥有其他选择,这很简单,但肤色略显:)

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);

Output: 输出:

some cool color #{1} more cool colors #{2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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