0
点赞
收藏
分享

微信扫一扫

Java String replace replaceAll replaceFirst 执行效果笔记

q松_松q 2022-04-25 阅读 55
java

Java String replace replaceAll replaceFirst 执行效果笔记

代码

public static void main(String[] args) {
	String aa = "asdfghjklzxcvbnmasdfghjklzxcvbnmasdfghjklzxcvbnm";
	System.out.println(aa.replace('b', '1'));
	System.out.println(aa.replace("bnm", "123"));
	System.out.println(aa.replaceAll("bnm", "123"));
	System.out.println(aa.replaceFirst("bnm", "123"));
}

结果

asdfghjklzxcv1nmasdfghjklzxcv1nmasdfghjklzxcv1nm
asdfghjklzxcv123asdfghjklzxcv123asdfghjklzxcv123
asdfghjklzxcv123asdfghjklzxcv123asdfghjklzxcv123
asdfghjklzxcv123asdfghjklzxcvbnmasdfghjklzxcvbnm

replace 和 replaceAll 的效果都是 全部替换
replaceFirst 的效果是 替换首次出现的字符

/**
 * Returns a string resulting from replacing all occurrences of
 * {@code oldChar} in this string with {@code newChar}.
 * <p>
 * If the character {@code oldChar} does not occur in the
 * character sequence represented by this {@code String} object,
 * then a reference to this {@code String} object is returned.
 * Otherwise, a {@code String} object is returned that
 * represents a character sequence identical to the character sequence
 * represented by this {@code String} object, except that every
 * occurrence of {@code oldChar} is replaced by an occurrence
 * of {@code newChar}.
 * <p>
 * Examples:
 * <blockquote><pre>
 * "mesquite in your cellar".replace('e', 'o')
 *         returns "mosquito in your collar"
 * "the war of baronets".replace('r', 'y')
 *         returns "the way of bayonets"
 * "sparring with a purple porpoise".replace('p', 't')
 *         returns "starring with a turtle tortoise"
 * "JonL".replace('q', 'x') returns "JonL" (no change)
 * </pre></blockquote>
 *
 * @param   oldChar   the old character.
 * @param   newChar   the new character.
 * @return  a string derived from this string by replacing every
 *          occurrence of {@code oldChar} with {@code newChar}.
 */
public String replace(char oldChar, char newChar) {
    if (oldChar != newChar) {
        int len = value.length;
        int i = -1;
        char[] val = value; /* avoid getfield opcode */

        while (++i < len) {
            if (val[i] == oldChar) {
                break;
            }
        }
        if (i < len) {
            char buf[] = new char[len];
            for (int j = 0; j < i; j++) {
                buf[j] = val[j];
            }
            while (i < len) {
                char c = val[i];
                buf[i] = (c == oldChar) ? newChar : c;
                i++;
            }
            return new String(buf, true);
        }
    }
    return this;
}
/**
 * Replaces the first substring of this string that matches the given <a
 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
 * given replacement.
 *
 * <p> An invocation of this method of the form
 * <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
 * yields exactly the same result as the expression
 *
 * <blockquote>
 * <code>
 * {@link java.util.regex.Pattern}.{@link
 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
 * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
 * java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>)
 * </code>
 * </blockquote>
 *
 *<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#replaceFirst}.
 * 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 substituted for the first match
 *
 * @return  The resulting {@code String}
 *
 * @throws  PatternSyntaxException
 *          if the regular expression's syntax is invalid
 *
 * @see java.util.regex.Pattern
 *
 * @since 1.4
 * @spec JSR-51
 */
public String replaceFirst(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}

/**
 * Replaces each substring of this string that matches the given <a
 * href="../util/regex/Pattern.html#sum">regular expression</a> with the
 * given replacement.
 *
 * <p> An invocation of this method of the form
 * <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
 * yields exactly the same result as the expression
 *
 * <blockquote>
 * <code>
 * {@link java.util.regex.Pattern}.{@link
 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
 * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
 * java.util.regex.Matcher#replaceAll replaceAll}(<i>repl</i>)
 * </code>
 * </blockquote>
 *
 *<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 substituted for each match
 *
 * @return  The resulting {@code String}
 *
 * @throws  PatternSyntaxException
 *          if the regular expression's syntax is invalid
 *
 * @see java.util.regex.Pattern
 *
 * @since 1.4
 * @spec JSR-51
 */
public String replaceAll(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

/**
 * Replaces each substring of this string that matches the literal target
 * sequence with the specified literal replacement sequence. The
 * replacement proceeds from the beginning of the string to the end, for
 * example, replacing "aa" with "b" in the string "aaa" will result in
 * "ba" rather than "ab".
 *
 * @param  target The sequence of char values to be replaced
 * @param  replacement The replacement sequence of char values
 * @return  The resulting string
 * @since 1.5
 */
public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
            this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}

看源码 replace 的参数是 CharSequence 或者 char
        当参数是 char 时 用 newChar 替换掉 oldChar
        当参数为 CharSequence 时 最终调用的方法和 replaceAll 是同一个
replaceAll 的参数是 String ;支持字符串和正则表达式
        当参数传的是普通字符串时 效果与 replace 一致
replaceFirst 的参数是 String ; 支持字符串和正则表达式
         替换首次匹配到的字符

参考博客

举报

相关推荐

【Java源码分析】String 替换 replace

0 条评论