正则表达式
String.matches();返回true或false str.matches("java");
正则表达式 匹配 示例
x 指定字符x str==str
. 任意单个字符,除了换行符 str==s.r
(ab|cd) ab或cd apple==a(pp|dd)le
[abc] a||b||c apple==a[pqre]ple
[^abc] 除a||b||c apple==a[ ^pqrs]ple
[a-z] a-z apple==[a-q]pple
[^a-z] 除a-z apple==[ ^b-c]pple
[a-e[m-p]] a-e||m-p apple==[a-c[d-e]]pple
[a-e&&[c-p]] a-e和c-p的交集 apple==[a-e&&[c-p]]pple
\d 数字[0-9] 1234==123[\\d]
\D 非数字 apple==[\\D]pple
\w 数字,字母,_ apple==[\\w]pple
\W 非w &apple==[\\W]apple
\s 空白字符 apple 2==apple[\\s]2
\S 非空白字符 apple==[\\S]pple
p* 0-n次出现p aaaa==a* abab==ab*
p+ 1-n次出现p a==a+b* apple==(ap)+b*
p? 0||1次出现p apple==a?pple
p{n} n次出现p apple==ap{2}
p{n,} >=n次出现p aaa==a{2,}
p{n,m} [n,m)次出现p aaaa==a{1,5}
\p{p} 标点符号 a&p==a\\p{P}p
代码
public class fifth {
public static void main(String[] args) {
String str = "apple";
if(str.matches("apple")) {System.out.println("true");}
if(str.matches("a.ple")) {System.out.println("true");}
if(str.matches("ap(pl|pp)e")) {System.out.println("true");}
if(str.matches("app[lab]e")) {System.out.println("true");}
if(str.matches("app[^ab]e")) {System.out.println("true");}
if(str.matches("app[a-l]e")) {System.out.println("true");}
if(str.matches("appl[^a-d]")) {System.out.println("true");}
if(str.matches("appl[a-e[l-p]]")) {System.out.println("true");}
if(str.matches("appl[a-e&&[c-p]]")) {System.out.println("true");}
String str1 = "1234";
if(str1.matches("appl[\\d]")) {System.out.println("true");}
if(str.matches("[\\D]pple")) {System.out.println("true");}
if(str.matches("[\\w]pple")) {System.out.println("true");}
String str2 = "&apple";
if(str2.matches("[\\W]apple")) {System.out.println("true");}
String str3 = "apple 2";
if(str3.matches("apple[\\s]2")) {System.out.println("true");}
if(str.matches("a[\\S]ple")) {System.out.println("true");}
String str4 = "aaaa";
if(str4.matches("a*")) {System.out.println("true");}
String str5 = "abab";
if(str5.matches("ab*")) {System.out.println("true");}
if(str.matches("ap+le")) {System.out.println("true");}
if(str.matches("a?ple")) {System.out.println("true");}
if(str.matches("ap{2}le")) {System.out.println("true");}
if(str.matches("ap{1,2}le")) {System.out.println("true");}
String str6 = "a&p";
if(str6.matches("a\\p{P}p")) {System.out.println("true");}
}
}
测试结果
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true