The first pit

JAVA escape character use often has some small holes, anyway I fell into, look at the code?

/ / output true System. Out. Println (" id = $id ". The contains (" $id ")); / / output id = $id System. Out. The println (" id = $id ". ReplaceAll (" $id ", "4")); / / output System id = 4. Out. Println (" id = $id ". ReplaceAll (" \ \ $id ", "4"));Copy the code

Contains does not have the same logic as replaceAll. Contains can be identified without escaping, which is what replaceAll does.

The second pit

In the example above, you found that contains doesn’t escape, right, but sometimes it does escape, and replaceAll needs to be escaped double, look at the code

Println ("d:\\Document". Contains ("\\"))); D: / / output/Document, need double escape System. Out. The println (" d: \ \ Document ". ReplaceAll (" \ \ \ \ ", "/"));Copy the code

The principle of analysis

\\ is an escape character that stands for \ in a Java string, and the first argument received by repleaseAll is a regular expression that requires the double input of \\\\ to represent \\.

$can be used directly in strings, so contains can be used directly. The regular replacement for $requires the use of \$.

Another option is to use quoteReplacement, as described in the JDK below.

Println ("d:\\Document". ReplaceAll (matcher.quotereplacement ("\\"),"/"); Println ("id=$id". ReplaceAll (matcher.quoterePlacement ("$ID "),"4"));Copy the code

Attach the JDK that

In the JDK’s replaceAll interpretation, the first argument received is an expression, and \ and $are special.

/** *<p> * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the * replacement string may cause the results to be different than if it were * being treated as a literal replacement string; see * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}. * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special * meaning of these characters, if desired. * * @param regex * the regular expression to which this string is to be matched * @param replacement * the String to be replaced for each match * * @since 1.4 */ public string replaceAll(String regex, String replacement) { return Pattern.compile(regex).matcher(this).replaceAll(replacement); }Copy the code

Contains in the JDK, receives a string


    /**
     * Returns true if and only if this string contains the specified
     * sequence of char values.
     *
     * @param s the sequence to search for
     * @return true if this string contains {@code s}, false otherwise
     * @since 1.5
     */
    public boolean contains(CharSequence s) {
        return indexOf(s.toString()) >= 0;
    }
Copy the code