Java正则表达式替换文本中的字符串

时间:2015-03-04 21:43:51

标签: java regex string

我有一个大字符串,我会看到一系列数字。我必须在数字前加一个字符。让我们举一个例子。我的字符串是..

String s= "Microsoft Ventures' start up \"98756\" accelerator wrong launched in apple in \"2012\" has been one of the most \"4241\" prestigious such programs in the country.";

我在Java中寻找一种方法在每个数字前面添加一个字符。所以我希望修改后的字符串看起来像......

String modified= "Microsoft Ventures' start up \"x98756\" accelerator wrong launched in apple in \"x2012\" has been one of the most \"x4241\" prestigious such programs in the country.";

我如何用Java做到这一点?

2 个答案:

答案 0 :(得分:2)

找到数字部分的正则表达式将是"\"[0-9]+\""。我将要做的方法是逐字循环原始字符串,如果单词与模式匹配,则替换它。

String[] tokens = s.split(" ");
String modified = "";
for (int i = 0 ; i < tokens.length ; i++) {
    // the digits are found
    if (Pattern.matches("\"[0-9]+\"", tokens[i])) {
        tokens[i] = "x" + tokens[i];
    }
    modified = modified + tokens[i] + " ";
}

代码只是给你一个想法,请自己优化(使用StringBuilder连接字符串等)。

答案 1 :(得分:0)

我能看到的最好的方法是将字符串分成各种sbustrings并将字符附加到其上。如下所示:

 String s="foo \67\ blah \89\"
 String modified=" ";
 String temp =" "; 
 int index=0;
 char c=' ';
 for(int i=0; i<s.length(); ++i) {
   c=s.charAt(i);
   if (Character.isDigit(c)) {
     temp=s.substring(index, i-1);
     modified=modified+temp+'x';
     int j=i;
        while(Character.isDigit(c)) {
           modified+=s[j];
           ++j;
           c=s.charAt(j);
        }
     index=j;
   }
 }