Section1 Pattern
首先理解这个单词:Pattern
Pattern 是什么意思?
中文译为模式,在深度学习领域,有所谓的模式识别的概念
手机号是一种模式,邮箱是也是一种模式,网址又是另外一直模式
Section2 ^和$ 使用
假设我想判断一个字符串是否以The开头要怎么做
System.out.println(Pattern.matches("^The.*", "The gril") + "");
以The结尾的呢?
System.out.println(Pattern.matches(".*The$", "gril The") + "");
^代表开头,$代表结尾
Section3 * , + , ?
先看* (0个或多个)
System.out.println(Pattern.matches("^ab*", "a") + ""); System.out.println(Pattern.matches("^ab*", "ab") + ""); System.out.println(Pattern.matches("^ab*", "abb") + "");true
true
true
再看+(1个或更多)
System.out.println(Pattern.matches("^ab+", "a") + ""); System.out.println(Pattern.matches("^ab+", "ab") + ""); System.out.println(Pattern.matches("^ab+", "abb") + "");false
true
true
然后看?(零个或一个)
System.out.println(Pattern.matches("^ab?", "a") + ""); System.out.println(Pattern.matches("^ab?", "ab") + ""); System.out.println(Pattern.matches("^ab?", "abb") + "");
true true false
Section4 {} 表示次数
ab{2} ==》a后面两个b
ab{2,} ==》a后面两个或更多个b
ab{3,5} ==>a后面3到5个b
==========================================
其实 * ===》{0,}
+ ===》{1,}
? ===》{0,1}
Section5 |
| 逻辑或
(1) ab|ba ===>ab或ba
(2)(ab|ba)cd ===>abcd 或bacd
System.out.println(Pattern.matches("^(ab|ba)cd", "abcd") + "");
System.out.println(Pattern.matches("^(ab|ba)cd", "bacd") + "");true
true
(a|b)*c ===> ab混合后面来个c
System.out.println(Pattern.matches("^(a|b)*c", "abc") + ""); System.out.println(Pattern.matches("^(a|b)*c", "abbbaac") + ""); System.out.println(Pattern.matches("^(a|b)*c", "baabbaac") + "");
本文介绍了正则表达式的概念及基本用法,包括模式匹配、特殊字符如^、$、*、+、?的作用,以及如何指定匹配次数等。通过实例演示了如何判断字符串的开头和结尾模式,重复模式的数量限制,以及使用逻辑或操作符进行多种模式的选择。
289

被折叠的 条评论
为什么被折叠?



