1. 程式人生 > >java編程思想-第13章-某些練習題

java編程思想-第13章-某些練習題

運行 ngs als ack mat tool spa replace color

. 匹配任意一個字符

* 表示匹配0個或多個前面這個字符

+ 表示1個或多個前面這個字符

? 表示0個或1個前面這個字符

^ 表示一行的開始   ^[a-zA-Z] :表示開頭是a-z或者A-Z

  [^0-9] :表示不是數字,除數字以外的

$ 表示一行的結束

第七題:

package net.mindview.strings.test7;

public class Test7 {

    public static void main(String[] args) {
        //兩種寫法都可以
        String regex = "^[A-Z].*\\.$";//"^[A-Z].*\\."這樣也對
String regex1 = "\\p{Upper}.*\\.$"; String str = "D."; String str1 = "Dfasdfasfasfdasfdasfasfasdf."; String str2 = "Dfasdfasfasfdasfdasfasfasdf.E"; System.out.println(str.matches(regex)); System.out.println(str1.matches(regex)); System.out.println(str2.matches(regex)); System.out.println(str.matches(regex1)); System.out.println(str1.matches(regex1)); System.out.println(str2.matches(regex1)); } }

運行結果:

true
true
false
true
true
false

第八題

package net.mindview.strings;

import java.util.Arrays;

public class Splitting {

    public static String knights = "Then, when you have found the shrubbery, you must cut down the mightiest tree in the forest... with... a herring!";

    public static void split(String regex){
        System.out.println(Arrays.toString(knights.split(regex)));
    }
    public static void main(String[] args) {
        //表示的時按照空格分割字符串
        //運行結果:[Then,, when, you, have, found, the, shrubbery,, you, must, cut, down, the, mightiest, tree, in, the, forest..., with..., a, herring!]
        split(" ");
        
        //表示按照非單次字符分割字符串--這裏的非單次字符是空格和,
        //運行結果:[Then, when, you, have, found, the, shrubbery, you, must, cut, down, the, mightiest, tree, in, the, forest, with, a, herring]
        split("\\W+");
        //這個表示:費單次字符之前帶n的地方進行分割字符串 這裏的分割符是n空格和n,
        //運行結果:[The, whe, you have found the shrubbery, you must cut dow, the mightiest tree i, the forest... with... a herring!]
        split("n\\W+");
    }

}
package net.mindview.strings.test8;

import net.mindview.strings.Splitting;

public class Test8 {
    
    public static void main(String[] args) {
        String regex = "the|you";
        Splitting.split(regex);
    }
}

第九題

package net.mindview.strings.test9;

import net.mindview.strings.Splitting;

public class Test9 {
    public static void main(String[] args) {
        String regex = "A|E|I|O|U|a|e|i|o|u";
        //通過嵌入式標誌表達式  (?i) 也可以啟用不區分大小寫的匹配。
        String regex1 = "(?i)a|e|i|o|u";
        //[abc] 表示a或b或c
        String regex2 = "(?i)[aeiou]";
        System.out.println(Splitting.knights.replaceAll(regex, "_"));
        System.out.println(Splitting.knights.replaceAll(regex1, "_"));
        System.out.println(Splitting.knights.replaceAll(regex2, "_"));
    }
}

java編程思想-第13章-某些練習題