正则表达式

正则表达式 

String.matches();返回true或false
str.matches("java");
正则表达式匹配示例
x指定字符xstr==str
.任意单个字符,除了换行符str==s.r
(ab|cd)ab或cdapple==a(pp|dd)le
[abc]a||b||capple==a[pqre]ple
[^abc]除a||b||capple==a[ ^pqrs]ple
[a-z]a-zapple==[a-q]pple
[^a-z]除a-zapple==[ ^b-c]pple
[a-e[m-p]]a-e||m-papple==[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次出现paaaa==a* abab==ab*
p+1-n次出现pa==a+b* apple==(ap)+b*
p?0||1次出现papple==a?pple
p{n}n次出现papple==ap{2}
p{n,}>=n次出现paaa==a{2,}
p{n,m}[n,m)次出现paaaa==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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值