[20-05-26][Thinking in Java 45]Java String 3 - Replace
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了[20-05-26][Thinking in Java 45]Java String 3 - Replace,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2373字,纯文字阅读大概需要4分钟。
内容图文
![[20-05-26][Thinking in Java 45]Java String 3 - Replace](/upload/InfoBanner/zyjiaocheng/631/ad15bb5642904353a35b270e8faa8b29.jpg)
1 package test_21_3; 2 3 import java.util.regex.Matcher; 4 import java.util.regex.Pattern; 5 6 public class ReplaceString { 7 8 public static void main(String[] args) { 9 10 String str = "Twas brillig, and the slithy toves\n" + 11 "Did gyre and gimble in the wabe.\n" + 12 "All mimsy were the borogoves,\n" + 13 "Beware the Jabberwock, my son,\n" + 14 "The jaws that bite, the claws that catch.\n" + 15 "Beware the Jubjub bird, and shun\n" + 16 "The frumious Bandersnatch."; 17 18 String regex1 = "\\bb\\w+\\b"; 19 // 替换第一个匹配项 20 String srf = str.replaceFirst(regex1, "[ReplaceFirst]"); 21 22 System.out.println(srf); 23 System.out.println("---------------"); 24 25 String regex2 = "\\ba\\w+\\b"; 26 // 替换所有匹配项 27 String sra = str.replaceAll(regex2, "[ReplaceAll]"); 28 29 System.out.println(sra); 30 System.out.println("----------------"); 31 32 StringBuffer sbuf = new StringBuffer(); 33 String regex3 = "[aeiou]"; 34 Pattern p = Pattern.compile(regex3); 35 Matcher m = p.matcher(str); 36 37 // 替换前15个匹配项 38 for (int i = 0; i < 15; i++) { 39 m.find(); 40 m.appendReplacement(sbuf, m.group().toUpperCase()); 41 } 42 // 将剩下的部分复制进sbuf 43 m.appendTail(sbuf); 44 45 System.out.println(sbuf); 46 47 } 48 }
结果如下:
Twas [ReplaceFirst], and the slithy toves
Did gyre and gimble in the wabe.
All mimsy were the borogoves,
Beware the Jabberwock, my son,
The jaws that bite, the claws that catch.
Beware the Jubjub bird, and shun
The frumious Bandersnatch.
---------------
Twas brillig, [ReplaceAll] the slithy toves
Did gyre [ReplaceAll] gimble in the wabe.
All mimsy were the borogoves,
Beware the Jabberwock, my son,
The jaws that bite, the claws that catch.
Beware the Jubjub bird, [ReplaceAll] shun
The frumious Bandersnatch.
----------------
TwAs brIllIg, And thE slIthy tOvEs
DId gyrE And gImblE In thE wabe.
All mimsy were the borogoves,
Beware the Jabberwock, my son,
The jaws that bite, the claws that catch.
Beware the Jubjub bird, and shun
The frumious Bandersnatch.
内容总结
以上是互联网集市为您收集整理的[20-05-26][Thinking in Java 45]Java String 3 - Replace全部内容,希望文章能够帮你解决[20-05-26][Thinking in Java 45]Java String 3 - Replace所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。