简体   繁体   中英

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

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?

The regex to find the numerical part will be "\\"[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).

The best way I could see to do this would be to split up the string into various sbustrings and append characters onto it. 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;
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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