. 匹配任意一个字符
* 表示匹配 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, "_"));
- }
- }
来源: http://www.bubuko.com/infodetail-2612723.html