stephanbauer: Backslashes in replaceAll

Hallo zusammen,

mein Code sieht etwa wir folgt aus:

  
String text0 = "irgendeintext ..."  
String text1 = "bla blub bla";  
String text2 = text1.replaceAll("blub", "[\w\d]+"); // <--- wieviele Backslashes  
String text3 = text0.replaceAll("aaa" + text2 + "bbb", "irgendwas");  

Wieviele Backslashes brauche ich nun bei text1.replaceAll damit es dann in text0.replaceAll als regulärer Ausdruck verwendet wird und warum?

Vielen Dank
sb

  1. Hallo,

    String text2 = text1.replaceAll("blub", "[\w\d]+"); // <--- wieviele Backslashes

    Wieviele Backslashes brauche ich nun bei text1.replaceAll damit es dann in text0.replaceAll als regulärer Ausdruck verwendet wird und warum?

    Beantwortet folgendes deine Frage schon?

    "Backslashes within string literals in Java source code are interpreted as required by the Java Language Specification as either Unicode escapes or other character escapes. It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\b" matches a word boundary. The string literal "(hello)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\(hello\)"  must be used."

    Dieser Absatz entstammt aus der Klassendokumentation von java.util.regex.Pattern.

    Gruß
    Slyh

    1. Beantwortet folgendes deine Frage schon?

      Leider nicht, mit
      String text2 = text1.replaceAll("blub", "[\w\d]+");
      steht in text2 nur [wd]+

      Aber ich habe es jetzt auch mit [a-zA-Z0-9]+ ausprobiert und es scheint, dass es in
      String text3 = text0.replaceAll("aaa" + text2 + "bbb", "irgendwas");
      einfach nicht als regulärer Ausdruck verwendet wird.

      1. Hallo,

        Leider nicht, mit
        String text2 = text1.replaceAll("blub", "[\w\d]+");
        steht in text2 nur [wd]+

        Das könnte daran liegen, daß du die beiden Parameter vertauchst hast:

          
          String replaceAll(String regex, String replacement)  
        
        

        Gruß
        Slyh