【问题标题】:How to replace a specific string in Java?如何替换Java中的特定字符串?
【发布时间】:2016-11-20 07:14:23
【问题描述】:

我通常不寻求帮助,但在这里我真的需要它。
我有以下代码示例:

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

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

我有一个问题,我如何只替换字符串中不包含 aabaa 部分。
所以控制台输出是:

-- aab -- aab

我还有一个例子:

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

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

我只想替换单个字符,而不是所有放在一起的相同字符。
所以控制台输出是:

111111111 -

对于此类情况,是否有任何 Java 快捷方式?我想不通,如何只替换字符串的特定部分。
任何帮助将不胜感激:)

【问题讨论】:

    标签: java string replace


    【解决方案1】:

    你可以使用正则表达式

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

    解释:

    • String.replaceAll 采用与 String.replace 相反的正则表达式, String.replace 采用乱码替换
    • (?=reg) 正则表达式的右侧部分必须后跟与正则表达式 reg 匹配的字符串,但只会捕获右侧部分
    • [^1]* 表示从 0 到任意数量的不同于 '1' 的字符的序列
    • $ 表示到达字符串的末尾

    用简单的英语,这意味着:请将所有出现的'1' 字符替换为空字符串,后跟任意数量的不同于'1' 的字符,直到字符串的结尾

    【讨论】:

    • 看其他答案,我可能误解了这个问题。留作记录
    【解决方案2】:

    您可以在String.replaceAll(String, String) 中使用正则表达式。通过使用单词边界 (\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);
    }
    

    输出(按要求)

    -- aab -- aab
    111111111 -
    

    【讨论】:

      【解决方案3】:

      我们可以使用 Java 中的 StringTokenizer 来实现任何类型的输入的解决方案。以下是示例解决方案,

      公共类 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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多