Home java Java string substitution

Java string substitution

Author

Date

Category

Method string = string.replace ("a", "b"); will replace all letters. But what if only the freestanding ones need to be replaced? That is, we change "a" , but "aa" remains to itself. Is there a way to somehow implement this?


Answer 1, authority 100%

Use a regular expression: (? & lt;! a) a (?! a) , while the adjacent characters “a” like “aaaa” are ignored.

  • (? & lt;! a) any character not “a” before character “a”
  • a the character “a” itself, which we replace
  • (?! a) any character not “a” after the character “a”

    Sample code how to use

    public static void main (String [] args) {
      String testString = "amaaaamaaaamkkjhatapa";
      System.out.println (testString.replaceAll ("(? & Lt;! A) a (?! A)", "."));
    }
    

Console output .maaaamaaaamkkjh.t.p.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions