Java String replace replaceAll replaceFirst 执行效果笔记
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 ; 支持字符串和正则表达式
替换首次匹配到的字符
参考博客
https://wenku.baidu.com/view/39b0d047deccda38376baf1ffc4ffe473368fdea.html
https://blog.csdn.net/atongmu2017/article/details/103889830
https://www.jb51.net/article/157844.htm
Java String replace replaceAll replaceFirst 执行效果笔记相关推荐
- java string replace 重载_关于Java:如何使用replace(char,char)替换字符b的所有实例为空...
如何使用replace(char,char)将字符" b"的所有实例全部替换为空. 例如: Hambbburger to Hamurger 编辑:有一个约束,我只能使用1.4.2, ...
- Java String关于replaceall函数转义字符的一个小贴士
1.在使用replaceall函数对字符串进行特定字符替换时,发现带转义字符的\要特殊处理. 2.参考代码如下: String str="http:\u002F\u002Fi.ebayimg ...
- java String和StringBuilder的执行效率
//使用字符流读取文件对话框选中的文件 BufferedReader bufFileRead = new BufferedReader ( new FileReader(fileDialog.g ...
- `java`学习笔记(十二)`Java`--`String``StringBuffer``StringBuilder`
Java–String&&StringBuffer&&StringBuilder 文章目录 `Java`--`String`&&`StringBuffe ...
- java replace无效_Java String.replace()方法无效的原因及解决方式
首先我们来看个例子 public class Demo1 { public static void main(String[] args) { String aa="abcd"; ...
- java中replace的用法_Java String replace() 使用方法及示例
Java String replace() 使用方法及示例 Java String replace()方法用 新的字符/文本 替换字符串中每个匹配的旧字符/文本. replace()方法的语法是 st ...
- java replacefirst第n_Java中replace()、replaceFirst()和replaceAll()区别
str.replace(str中被替换的,替换后的字符) replace和replaceAll是JAVA中常用的替换字符的方法,它们的区别是: 1)replace的参数是char和CharSequen ...
- Java教程:Java字符串的替换(replace()、replaceFirst()和replaceAll())
本篇文章由 泉州SEO www.234yp.com 整理发布,Java教程 www.234yp.com/Article/198077.html 谢谢合作! Java教程在 Java 中,String ...
- Java字符串的替换(replace()、replaceFirst()和replaceAll())
在 Java 中,String 类提供了 3 种字符串替换方法,分别是 replace().replaceFirst() 和 replaceAll(),本文将详细介绍它们的使用方法. replace( ...
- java replaceall函数_JAVA中string.replace和string.replaceAll的区别及用法
展开全部 JAVA中string.replace()和string.replaceAll()的区别及用法乍一看,字面上理解好像replace只替换第一个出现的字符(受javascript的影响),32 ...
最新文章
- 【Nodejs】记一次图像识别的冒险
- 无锁数据结构三:无锁数据结构的两大问题
- 金蝶系统服务器要求,金蝶服务器安装及其相关要求.doc
- 第六节:框架搭建之EF的Fluent Api模式的使用流程
- Linux通过文件大小查找,linux 根据文件大小查找文件
- ruby 新建对象_Ruby面向对象编程简介
- IntelliJ IDEA + Maven环境编写第一个hadoop程序
- (20)System Verilog利用clocking块产生输出信号延迟激励
- 【kafka】kafka 0.10以及1.x版本的kafka topic 分区扩容
- Element ui 中的Upload用法
- UI完美素材|(Watch展示篇)Mockups动态图提案模板
- 过去一年顶级借贷服务商BTC总托管资产平均增长超700%
- 老手萌新学习composer的使用
- e search index.php,php操作elastcisearch使用ik分词做搜索,搜索结果总为空
- 软件的一些标号及对应版本
- java常用类objet,Java基础-常用API-Object类
- java实现杨辉三角
- matlab语法——数据类型、科学计数法和注释
- 好玩的黑客游戏(过把黑客的瘾)
- uniapp实现苹果支付流程
热门文章
- Java笔记:final修饰符
- 新概念英语(1-29)Come in, Amy.
- LintCode Coins in a Line II
- Java EE Servlet 几个path
- Activiti中的log4j(slf4j)的配置
- smartform---条形码技术详解
- Leetcode: Reorder List Summary: Reverse a LinkedList
- mysql ODBC连接配置
- java调用闭包对象_任务不可序列化:java.io.NotSerializableException仅在类而不是对象上调用闭包外的函数时...
- 拓端tecdat|r语言中对LASSO回归,Ridge岭回归和弹性网络Elastic Net模型实现|视频