[20-05-26][Thinking in Java 45]Java String 3 - Replace

 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.

猜你喜欢

转载自www.cnblogs.com/mirai3usi9/p/12969645.html