简体   繁体   English

如何用Java替换特定的字符串?

[英]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. 我有一个问题,我怎么只替换不AAB包括字符串的AA部分。
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? 是否有类似这些情况的Java快捷方式? 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) . 您可以使用String.replaceAll(String, String)正则表达式 By using word boundaries ( \\b ), something like 通过使用单词边界( \\b ),类似于

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 String.replaceAllString.replace相反地​​采用正则表达式,它取代了一个litteral
  • (?=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 (?=reg)正则表达式的右边部分必须跟一个匹配正则表达式reg的字符串,但只捕获正确的部分
  • [^1]* means a sequence from 0 to any number of characters different from '1' [^1]*表示从0到任意数量不同于'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 . 用简单的英语,这意味着: 请用空字符串替换所有出现的'1'字符,后跟任意数量的不同于'1'的字符,直到字符串结尾

We can use the StringTokenizer present in Java to acheive the solution for any kind of input. 我们可以使用Java中的StringTokenizer来实现任何类型输入的解决方案。 Below is the sample solution, 以下是示例解决方案,

public class StringTokenizerExample { 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);
}

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

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