I'm trying to use something like

public static final Pattern p1 = Pattern.compile("\[(.*?)\]"); public static final Pattern p1 = Pattern.compile("\[(\w)\]"); 

what I get:

Invalid escape sequence (valid ones are \ b \ t \ n \ f \ r \ "\ '\)

Why?

    2 answers 2

    The \ character is used in java for escape sequences (the very \b \t \n \f \r \" \' that the compiler speaks of. Therefore, to use it in the string, you need to escape:

     public static final Pattern p1 = Pattern.compile("\\[(.*?)\\]"); public static final Pattern p1 = Pattern.compile("\\[(\\w)\\]"); 
    • Yes, it worked, but now you need to escape double quotes like brackets. Here, this method does not work, because the IDE considers the quote to be the end of the line and returns an error. To this I answer this line. Pattern.compile ("\\\\" + (char) 34 + "(. *?)" + "\\\\" + (char) 34); Will it work? Or is it better such a string Pattern.compile ("\\\\\\" (. *?) \\\\\\\ ""); - igumnov
    • Pattern.compile("\\\"(.?)\\\""); quite adequate option - Nofate
    • Matryoshka pattern :-) Escape Escape Eskeypovich. - karmadro4
    • four
      Such questions only testify in favor of the fact that the regexps evil turned out to be in Java by mistake! - Barmaley
    • one
      But for these thoughts I like barmaley =) - Gorets

    Duplicate the slash: " \\[(.*?)\\] "