简体   繁体   English

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

[英]Java Regular expression to replace a string in text

I have a large string where I will see a sequence of digits. 我有一个很大的字符串,在这里我会看到一个数字序列。 I have to append a character in front of the number. 我必须在数字前添加一个字符。 lets take an example. 让我们举个例子。 my string is.. 我的绳子是..

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.";

I am looking for a way in Java to add a character in front of each number.so I am expecting the modified string will looks like... 我正在寻找一种在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.";

How do I do that in Java? 如何在Java中做到这一点?

The regex to find the numerical part will be "\\"[0-9]+\\"" . 查找数字部分的正则表达式为"\\"[0-9]+\\"" The approach I will do is loop through the original string by word, if the word matches the pattern, replace it. 我将采用的方法是逐字遍历原始字符串,如果单词与模式匹配,则将其替换。

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] + " ";
}

The code is simply to give you the idea, please optimize it yourself (using StringBuilder to concatenate strings and etc). 代码只是为了给您一个想法,请您自己对其进行优化(使用StringBuilder连接字符串等)。

The best way I could see to do this would be to split up the string into various sbustrings and append characters onto it. 我能看到的最好的方法是将字符串分成各种sbustring并在其上附加字符。 Something like the following: 类似于以下内容:

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

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

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