java编程思想-第13章-某些练习题

时间:2022-04-11 11:41:03

. 匹配任意一个字符

* 表示匹配0个或多个前面这个字符

+ 表示1个或多个前面这个字符

? 表示0个或1个前面这个字符

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

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

$ 表示一行的结束

\w 表示词字符[a-zA-Z0-9]

\W 表示非词字符[^\w]

第七题:

  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, "_")); } }