简体   繁体   中英

How to replace a specific string in Java?

I usually don't ask for help but here I really need it.
I have the following code example:

String text = "aa aab aa aab";
text = text.replace("aa", "--");
System.out.println(text);

Console output: -- --b -- --b

I have a question, how do I only replace aa parts of the string not aab included.
So the console output is:

-- aab -- aab

I have another example:

String text = "111111111 1";
text = text.replace("1", "-");
System.out.println(text);

Console output: --------- -

I only want to replace a single character, not all the same ones who are placed together.
So the console output is:

111111111 -

Are there any Java shortcuts for situations like these? I can't figure it out, how to only replace specific part of the string.
Any help would be appreciated :)

You could use a regular expression with String.replaceAll(String, String) . By using word boundaries ( \\b ), something like

String[] texts = { "aa aab aa aab", "111111111 1" };
String[] toReplace = { "aa", "1" };
String[] toReplaceWith = { "--", "-" };
for (int i = 0; i < texts.length; i++) {
    String text = texts[i];
    text = text.replaceAll("\\b" + toReplace[i] + "\\b", toReplaceWith[i]);
    System.out.println(text);
}

Outputs (as requested)

-- aab -- aab
111111111 -

You can use a regex

String text = "111111111 1";
text = text.replaceAll("1(?=[^1]*$)", "");
System.out.println(text);

Explanation:

  • String.replaceAll takes a regex contrarily to String.replace which takes a litteral to replace
  • (?=reg) the right part of the regex must be followed by a string matching the regex reg , but only the right part will be captured
  • [^1]* means a sequence from 0 to any number of characters different from '1'
  • $ means the end of the string is reached

In plain english, this means: Please replace by an empty string all the occurrences of the '1' character followed by any number of characters different from '1' until the end of the string .

We can use the StringTokenizer present in Java to acheive the solution for any kind of input. Below is the sample solution,

public class StringTokenizerExample {

/**
 * @param args
 */
public static void main(String[] args) {
    String input = "aa aab aa aab";
    String output = "";
    String replaceWord = "aa";
    String replaceWith = "--";
    StringTokenizer st = new StringTokenizer(input," ");
    System.out.println("Before Replace: "+input);
    while (st.hasMoreElements()) {
        String word = st.nextElement().toString();
        if(word.equals(replaceWord)){
            word = replaceWith;
            if(st.hasMoreElements()){
                word = " "+word+" ";
            }else{
                word = " "+word;
            }
        }
        output = output+word;
    }
    System.out.println("After Replace: "+output);
}

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