What is equivalent to .replaceSecond or .replaceThird?











up vote
3
down vote

favorite












In this code, we remove the substring "luna" from email string using the .replaceFirst method. We are removing the characters in between + and @. But this happens only in the first instance because we used .replaceFirst. What if we wanted to target the second instance of + and @ to remove "smith"?
Our output now is alice+@john+smith@steve+oliver@ but we want alice+luna@john+@steve+oliver@



public class Main {

public static void main(String args) {

String email = "alice+luna@john+smith@steve+oliver@";

String newEmail = email.replaceFirst("\+.*?@", "");

System.out.println(newEmail);

}
}









share|improve this question




















  • 1




    Use a regex to do this?
    – triplem
    yesterday















up vote
3
down vote

favorite












In this code, we remove the substring "luna" from email string using the .replaceFirst method. We are removing the characters in between + and @. But this happens only in the first instance because we used .replaceFirst. What if we wanted to target the second instance of + and @ to remove "smith"?
Our output now is alice+@john+smith@steve+oliver@ but we want alice+luna@john+@steve+oliver@



public class Main {

public static void main(String args) {

String email = "alice+luna@john+smith@steve+oliver@";

String newEmail = email.replaceFirst("\+.*?@", "");

System.out.println(newEmail);

}
}









share|improve this question




















  • 1




    Use a regex to do this?
    – triplem
    yesterday













up vote
3
down vote

favorite









up vote
3
down vote

favorite











In this code, we remove the substring "luna" from email string using the .replaceFirst method. We are removing the characters in between + and @. But this happens only in the first instance because we used .replaceFirst. What if we wanted to target the second instance of + and @ to remove "smith"?
Our output now is alice+@john+smith@steve+oliver@ but we want alice+luna@john+@steve+oliver@



public class Main {

public static void main(String args) {

String email = "alice+luna@john+smith@steve+oliver@";

String newEmail = email.replaceFirst("\+.*?@", "");

System.out.println(newEmail);

}
}









share|improve this question















In this code, we remove the substring "luna" from email string using the .replaceFirst method. We are removing the characters in between + and @. But this happens only in the first instance because we used .replaceFirst. What if we wanted to target the second instance of + and @ to remove "smith"?
Our output now is alice+@john+smith@steve+oliver@ but we want alice+luna@john+@steve+oliver@



public class Main {

public static void main(String args) {

String email = "alice+luna@john+smith@steve+oliver@";

String newEmail = email.replaceFirst("\+.*?@", "");

System.out.println(newEmail);

}
}






java string replace






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday









Prashant Gupta

739519




739519










asked yesterday









NoobCoder

717




717








  • 1




    Use a regex to do this?
    – triplem
    yesterday














  • 1




    Use a regex to do this?
    – triplem
    yesterday








1




1




Use a regex to do this?
– triplem
yesterday




Use a regex to do this?
– triplem
yesterday












4 Answers
4






active

oldest

votes

















up vote
2
down vote













You can find the second + like so:



int firstPlus = email.indexOf('+');
int secondPlus = email.indexOf('+', firstPlus + 1);


(You need to handle the case that there aren't two +s to find, if necessary).



Then find the following @:



int at = email.indexOf('@', secondPlus);


Then stitch it back together:



String newEmail = email.substring(0, secondPlus + 1) + email.substring(at);


or



String newEmail2 = new StringBuilder(email).delete(secondPlus + 1, at).toString();


Ideone demo






share|improve this answer






























    up vote
    1
    down vote













    Unfortunately Java doesn't have methods like replace second, replace third etc. You can either replaceAll (which will replace all occurences) OR invoce replaceFirst again on the already replaced string. That's basically replacing the second. If you want to replace ONLY the second - then you can do it with substrings or do a regex matcher and iterate on results.



      public static void main(String args) {

    String email = "alice+luna@john+smith@steve+oliver@";

    String newEmail = email.replaceFirst("\+.*?@", "");
    newEmail = newEmail .replaceFirst("\+.*?@", ""); //this replaces the second right? :)
    newEmail = newEmail .replaceFirst("\+.*?@", ""); // replace 3rd etc.

    System.out.println(newEmail);

    }





    share|improve this answer




























      up vote
      0
      down vote













      You can alternate value of parameter n in following replaceNth method to 2, 3 to perform exactly the same operation as that of replaceSecond or replaceThird. ( Note: this method can be applied in any other value of n. If nth pattern do not exist , it simply return given string ).



      import java.util.regex.Matcher;
      import java.util.regex.Pattern;

      public class Main {

      public static String replaceNth(String str, int n, String regex, String replaceWith) {
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(str);
      while (m.find()) {
      n--;
      if (n == 0) {
      return str.substring(0,m.start() + 1)+ replaceWith + str.substring(m.end() - 1);
      }
      }
      return str;
      }

      public static void main(String args) {
      String email = "alice+luna@john+smith@steve+oliver@";
      System.out.println(replaceNth(email, 2, "\+.*?@", ""));
      }
      }





      share|improve this answer




























        up vote
        0
        down vote













        I think it is better to encapsulate this logic into separate method, where String and group position are arguments.



        private static final Pattern PATTERN = Pattern.compile("([^+@]+)@");

        private static String removeSubstringGroup(String str, int pos) {
        Matcher matcher = PATTERN.matcher(str);

        while (matcher.find()) {
        if (pos-- == 0)
        return str.substring(0, matcher.start()) + str.substring(matcher.end() - 1);
        }

        return str;
        }


        Additionally, you can add more methods, to simplify using this util; like removeFirst() or removeLast()



        public static String removeFirst(String str) {
        return removeSubstringGroup(str, 0);
        }

        public static String removeSecond(String str) {
        return removeSubstringGroup(str, 1);
        }


        Demo:



        String email = "alice+luna@john+smith@steve+oliver@";
        System.out.println(email);
        System.out.println(removeFirst(email));
        System.out.println(removeSecond(email));
        System.out.println(removeSubstringGroup(email, 2));
        System.out.println(removeSubstringGroup(email, 3));


        Output:



        alice+luna@john+smith@steve+oliver@
        alice+@john+smith@steve+oliver@
        alice+luna@john+@steve+oliver@
        alice+luna@john+smith@steve+@
        alice+luna@john+smith@steve+oliver@


        Ideone demo






        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372287%2fwhat-is-equivalent-to-replacesecond-or-replacethird%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote













          You can find the second + like so:



          int firstPlus = email.indexOf('+');
          int secondPlus = email.indexOf('+', firstPlus + 1);


          (You need to handle the case that there aren't two +s to find, if necessary).



          Then find the following @:



          int at = email.indexOf('@', secondPlus);


          Then stitch it back together:



          String newEmail = email.substring(0, secondPlus + 1) + email.substring(at);


          or



          String newEmail2 = new StringBuilder(email).delete(secondPlus + 1, at).toString();


          Ideone demo






          share|improve this answer



























            up vote
            2
            down vote













            You can find the second + like so:



            int firstPlus = email.indexOf('+');
            int secondPlus = email.indexOf('+', firstPlus + 1);


            (You need to handle the case that there aren't two +s to find, if necessary).



            Then find the following @:



            int at = email.indexOf('@', secondPlus);


            Then stitch it back together:



            String newEmail = email.substring(0, secondPlus + 1) + email.substring(at);


            or



            String newEmail2 = new StringBuilder(email).delete(secondPlus + 1, at).toString();


            Ideone demo






            share|improve this answer

























              up vote
              2
              down vote










              up vote
              2
              down vote









              You can find the second + like so:



              int firstPlus = email.indexOf('+');
              int secondPlus = email.indexOf('+', firstPlus + 1);


              (You need to handle the case that there aren't two +s to find, if necessary).



              Then find the following @:



              int at = email.indexOf('@', secondPlus);


              Then stitch it back together:



              String newEmail = email.substring(0, secondPlus + 1) + email.substring(at);


              or



              String newEmail2 = new StringBuilder(email).delete(secondPlus + 1, at).toString();


              Ideone demo






              share|improve this answer














              You can find the second + like so:



              int firstPlus = email.indexOf('+');
              int secondPlus = email.indexOf('+', firstPlus + 1);


              (You need to handle the case that there aren't two +s to find, if necessary).



              Then find the following @:



              int at = email.indexOf('@', secondPlus);


              Then stitch it back together:



              String newEmail = email.substring(0, secondPlus + 1) + email.substring(at);


              or



              String newEmail2 = new StringBuilder(email).delete(secondPlus + 1, at).toString();


              Ideone demo







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited yesterday

























              answered yesterday









              Andy Turner

              78.3k878129




              78.3k878129
























                  up vote
                  1
                  down vote













                  Unfortunately Java doesn't have methods like replace second, replace third etc. You can either replaceAll (which will replace all occurences) OR invoce replaceFirst again on the already replaced string. That's basically replacing the second. If you want to replace ONLY the second - then you can do it with substrings or do a regex matcher and iterate on results.



                    public static void main(String args) {

                  String email = "alice+luna@john+smith@steve+oliver@";

                  String newEmail = email.replaceFirst("\+.*?@", "");
                  newEmail = newEmail .replaceFirst("\+.*?@", ""); //this replaces the second right? :)
                  newEmail = newEmail .replaceFirst("\+.*?@", ""); // replace 3rd etc.

                  System.out.println(newEmail);

                  }





                  share|improve this answer

























                    up vote
                    1
                    down vote













                    Unfortunately Java doesn't have methods like replace second, replace third etc. You can either replaceAll (which will replace all occurences) OR invoce replaceFirst again on the already replaced string. That's basically replacing the second. If you want to replace ONLY the second - then you can do it with substrings or do a regex matcher and iterate on results.



                      public static void main(String args) {

                    String email = "alice+luna@john+smith@steve+oliver@";

                    String newEmail = email.replaceFirst("\+.*?@", "");
                    newEmail = newEmail .replaceFirst("\+.*?@", ""); //this replaces the second right? :)
                    newEmail = newEmail .replaceFirst("\+.*?@", ""); // replace 3rd etc.

                    System.out.println(newEmail);

                    }





                    share|improve this answer























                      up vote
                      1
                      down vote










                      up vote
                      1
                      down vote









                      Unfortunately Java doesn't have methods like replace second, replace third etc. You can either replaceAll (which will replace all occurences) OR invoce replaceFirst again on the already replaced string. That's basically replacing the second. If you want to replace ONLY the second - then you can do it with substrings or do a regex matcher and iterate on results.



                        public static void main(String args) {

                      String email = "alice+luna@john+smith@steve+oliver@";

                      String newEmail = email.replaceFirst("\+.*?@", "");
                      newEmail = newEmail .replaceFirst("\+.*?@", ""); //this replaces the second right? :)
                      newEmail = newEmail .replaceFirst("\+.*?@", ""); // replace 3rd etc.

                      System.out.println(newEmail);

                      }





                      share|improve this answer












                      Unfortunately Java doesn't have methods like replace second, replace third etc. You can either replaceAll (which will replace all occurences) OR invoce replaceFirst again on the already replaced string. That's basically replacing the second. If you want to replace ONLY the second - then you can do it with substrings or do a regex matcher and iterate on results.



                        public static void main(String args) {

                      String email = "alice+luna@john+smith@steve+oliver@";

                      String newEmail = email.replaceFirst("\+.*?@", "");
                      newEmail = newEmail .replaceFirst("\+.*?@", ""); //this replaces the second right? :)
                      newEmail = newEmail .replaceFirst("\+.*?@", ""); // replace 3rd etc.

                      System.out.println(newEmail);

                      }






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered yesterday









                      Veselin Davidov

                      5,4861515




                      5,4861515






















                          up vote
                          0
                          down vote













                          You can alternate value of parameter n in following replaceNth method to 2, 3 to perform exactly the same operation as that of replaceSecond or replaceThird. ( Note: this method can be applied in any other value of n. If nth pattern do not exist , it simply return given string ).



                          import java.util.regex.Matcher;
                          import java.util.regex.Pattern;

                          public class Main {

                          public static String replaceNth(String str, int n, String regex, String replaceWith) {
                          Pattern p = Pattern.compile(regex);
                          Matcher m = p.matcher(str);
                          while (m.find()) {
                          n--;
                          if (n == 0) {
                          return str.substring(0,m.start() + 1)+ replaceWith + str.substring(m.end() - 1);
                          }
                          }
                          return str;
                          }

                          public static void main(String args) {
                          String email = "alice+luna@john+smith@steve+oliver@";
                          System.out.println(replaceNth(email, 2, "\+.*?@", ""));
                          }
                          }





                          share|improve this answer

























                            up vote
                            0
                            down vote













                            You can alternate value of parameter n in following replaceNth method to 2, 3 to perform exactly the same operation as that of replaceSecond or replaceThird. ( Note: this method can be applied in any other value of n. If nth pattern do not exist , it simply return given string ).



                            import java.util.regex.Matcher;
                            import java.util.regex.Pattern;

                            public class Main {

                            public static String replaceNth(String str, int n, String regex, String replaceWith) {
                            Pattern p = Pattern.compile(regex);
                            Matcher m = p.matcher(str);
                            while (m.find()) {
                            n--;
                            if (n == 0) {
                            return str.substring(0,m.start() + 1)+ replaceWith + str.substring(m.end() - 1);
                            }
                            }
                            return str;
                            }

                            public static void main(String args) {
                            String email = "alice+luna@john+smith@steve+oliver@";
                            System.out.println(replaceNth(email, 2, "\+.*?@", ""));
                            }
                            }





                            share|improve this answer























                              up vote
                              0
                              down vote










                              up vote
                              0
                              down vote









                              You can alternate value of parameter n in following replaceNth method to 2, 3 to perform exactly the same operation as that of replaceSecond or replaceThird. ( Note: this method can be applied in any other value of n. If nth pattern do not exist , it simply return given string ).



                              import java.util.regex.Matcher;
                              import java.util.regex.Pattern;

                              public class Main {

                              public static String replaceNth(String str, int n, String regex, String replaceWith) {
                              Pattern p = Pattern.compile(regex);
                              Matcher m = p.matcher(str);
                              while (m.find()) {
                              n--;
                              if (n == 0) {
                              return str.substring(0,m.start() + 1)+ replaceWith + str.substring(m.end() - 1);
                              }
                              }
                              return str;
                              }

                              public static void main(String args) {
                              String email = "alice+luna@john+smith@steve+oliver@";
                              System.out.println(replaceNth(email, 2, "\+.*?@", ""));
                              }
                              }





                              share|improve this answer












                              You can alternate value of parameter n in following replaceNth method to 2, 3 to perform exactly the same operation as that of replaceSecond or replaceThird. ( Note: this method can be applied in any other value of n. If nth pattern do not exist , it simply return given string ).



                              import java.util.regex.Matcher;
                              import java.util.regex.Pattern;

                              public class Main {

                              public static String replaceNth(String str, int n, String regex, String replaceWith) {
                              Pattern p = Pattern.compile(regex);
                              Matcher m = p.matcher(str);
                              while (m.find()) {
                              n--;
                              if (n == 0) {
                              return str.substring(0,m.start() + 1)+ replaceWith + str.substring(m.end() - 1);
                              }
                              }
                              return str;
                              }

                              public static void main(String args) {
                              String email = "alice+luna@john+smith@steve+oliver@";
                              System.out.println(replaceNth(email, 2, "\+.*?@", ""));
                              }
                              }






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered yesterday









                              Bishal Gautam

                              131211




                              131211






















                                  up vote
                                  0
                                  down vote













                                  I think it is better to encapsulate this logic into separate method, where String and group position are arguments.



                                  private static final Pattern PATTERN = Pattern.compile("([^+@]+)@");

                                  private static String removeSubstringGroup(String str, int pos) {
                                  Matcher matcher = PATTERN.matcher(str);

                                  while (matcher.find()) {
                                  if (pos-- == 0)
                                  return str.substring(0, matcher.start()) + str.substring(matcher.end() - 1);
                                  }

                                  return str;
                                  }


                                  Additionally, you can add more methods, to simplify using this util; like removeFirst() or removeLast()



                                  public static String removeFirst(String str) {
                                  return removeSubstringGroup(str, 0);
                                  }

                                  public static String removeSecond(String str) {
                                  return removeSubstringGroup(str, 1);
                                  }


                                  Demo:



                                  String email = "alice+luna@john+smith@steve+oliver@";
                                  System.out.println(email);
                                  System.out.println(removeFirst(email));
                                  System.out.println(removeSecond(email));
                                  System.out.println(removeSubstringGroup(email, 2));
                                  System.out.println(removeSubstringGroup(email, 3));


                                  Output:



                                  alice+luna@john+smith@steve+oliver@
                                  alice+@john+smith@steve+oliver@
                                  alice+luna@john+@steve+oliver@
                                  alice+luna@john+smith@steve+@
                                  alice+luna@john+smith@steve+oliver@


                                  Ideone demo






                                  share|improve this answer



























                                    up vote
                                    0
                                    down vote













                                    I think it is better to encapsulate this logic into separate method, where String and group position are arguments.



                                    private static final Pattern PATTERN = Pattern.compile("([^+@]+)@");

                                    private static String removeSubstringGroup(String str, int pos) {
                                    Matcher matcher = PATTERN.matcher(str);

                                    while (matcher.find()) {
                                    if (pos-- == 0)
                                    return str.substring(0, matcher.start()) + str.substring(matcher.end() - 1);
                                    }

                                    return str;
                                    }


                                    Additionally, you can add more methods, to simplify using this util; like removeFirst() or removeLast()



                                    public static String removeFirst(String str) {
                                    return removeSubstringGroup(str, 0);
                                    }

                                    public static String removeSecond(String str) {
                                    return removeSubstringGroup(str, 1);
                                    }


                                    Demo:



                                    String email = "alice+luna@john+smith@steve+oliver@";
                                    System.out.println(email);
                                    System.out.println(removeFirst(email));
                                    System.out.println(removeSecond(email));
                                    System.out.println(removeSubstringGroup(email, 2));
                                    System.out.println(removeSubstringGroup(email, 3));


                                    Output:



                                    alice+luna@john+smith@steve+oliver@
                                    alice+@john+smith@steve+oliver@
                                    alice+luna@john+@steve+oliver@
                                    alice+luna@john+smith@steve+@
                                    alice+luna@john+smith@steve+oliver@


                                    Ideone demo






                                    share|improve this answer

























                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      I think it is better to encapsulate this logic into separate method, where String and group position are arguments.



                                      private static final Pattern PATTERN = Pattern.compile("([^+@]+)@");

                                      private static String removeSubstringGroup(String str, int pos) {
                                      Matcher matcher = PATTERN.matcher(str);

                                      while (matcher.find()) {
                                      if (pos-- == 0)
                                      return str.substring(0, matcher.start()) + str.substring(matcher.end() - 1);
                                      }

                                      return str;
                                      }


                                      Additionally, you can add more methods, to simplify using this util; like removeFirst() or removeLast()



                                      public static String removeFirst(String str) {
                                      return removeSubstringGroup(str, 0);
                                      }

                                      public static String removeSecond(String str) {
                                      return removeSubstringGroup(str, 1);
                                      }


                                      Demo:



                                      String email = "alice+luna@john+smith@steve+oliver@";
                                      System.out.println(email);
                                      System.out.println(removeFirst(email));
                                      System.out.println(removeSecond(email));
                                      System.out.println(removeSubstringGroup(email, 2));
                                      System.out.println(removeSubstringGroup(email, 3));


                                      Output:



                                      alice+luna@john+smith@steve+oliver@
                                      alice+@john+smith@steve+oliver@
                                      alice+luna@john+@steve+oliver@
                                      alice+luna@john+smith@steve+@
                                      alice+luna@john+smith@steve+oliver@


                                      Ideone demo






                                      share|improve this answer














                                      I think it is better to encapsulate this logic into separate method, where String and group position are arguments.



                                      private static final Pattern PATTERN = Pattern.compile("([^+@]+)@");

                                      private static String removeSubstringGroup(String str, int pos) {
                                      Matcher matcher = PATTERN.matcher(str);

                                      while (matcher.find()) {
                                      if (pos-- == 0)
                                      return str.substring(0, matcher.start()) + str.substring(matcher.end() - 1);
                                      }

                                      return str;
                                      }


                                      Additionally, you can add more methods, to simplify using this util; like removeFirst() or removeLast()



                                      public static String removeFirst(String str) {
                                      return removeSubstringGroup(str, 0);
                                      }

                                      public static String removeSecond(String str) {
                                      return removeSubstringGroup(str, 1);
                                      }


                                      Demo:



                                      String email = "alice+luna@john+smith@steve+oliver@";
                                      System.out.println(email);
                                      System.out.println(removeFirst(email));
                                      System.out.println(removeSecond(email));
                                      System.out.println(removeSubstringGroup(email, 2));
                                      System.out.println(removeSubstringGroup(email, 3));


                                      Output:



                                      alice+luna@john+smith@steve+oliver@
                                      alice+@john+smith@steve+oliver@
                                      alice+luna@john+@steve+oliver@
                                      alice+luna@john+smith@steve+@
                                      alice+luna@john+smith@steve+oliver@


                                      Ideone demo







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited yesterday

























                                      answered yesterday









                                      oleg.cherednik

                                      4,1902916




                                      4,1902916






























                                           

                                          draft saved


                                          draft discarded



















































                                           


                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372287%2fwhat-is-equivalent-to-replacesecond-or-replacethird%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                                          Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                                          A Topological Invariant for $pi_3(U(n))$