zoukankan      html  css  js  c++  java
  • Java的String.matches不区分大小写正则表达式匹配示例

    需求:输入的cmd符合create,listall,delete三种形式,不用区分大小写

    写成函数:

        public static boolean isAllowed3Cmd(String cmd) {
            return cmd.matches("^(?i)(create|delete|listall)$");
        }

    正则式分析:

    ^...$:从字符串头到尾全部符合模式

    ?i:不区分大小写

    create|delete|listall:三选一

    完整测试代码:

    public class StringMatchesTest {
        public static void main(String[] args) {
            String[] arr= {"creat","create","Create","DELETE","LISTall","list","creat","del","listalllistall","deletecreate"};
            for(String cmd:arr) {
                System.out.println(String.format("String:%s %s pattern:%s",cmd,isAllowed3Cmd(cmd)?"matches":"dosen't match","'^(?i)(create|delete|listall)$'"));
            }
        }
        
        public static boolean isAllowed3Cmd(String cmd) {
            return cmd.matches("^(?i)(create|delete|listall)$");
        }
    }

    输出:

    String:creat dosen't match pattern:'^(?i)(create|delete|listall)$'
    String:create matches pattern:'^(?i)(create|delete|listall)$'
    String:Create matches pattern:'^(?i)(create|delete|listall)$'
    String:DELETE matches pattern:'^(?i)(create|delete|listall)$'
    String:LISTall matches pattern:'^(?i)(create|delete|listall)$'
    String:list dosen't match pattern:'^(?i)(create|delete|listall)$'
    String:creat dosen't match pattern:'^(?i)(create|delete|listall)$'
    String:del dosen't match pattern:'^(?i)(create|delete|listall)$'
    String:listalllistall dosen't match pattern:'^(?i)(create|delete|listall)$'
    String:deletecreate dosen't match pattern:'^(?i)(create|delete|listall)$'

    --2020年3月30日--

  • 相关阅读:
    《山里的日子(记录片)》观后感——回不去的农村
    Android事件分发传递
    《活着》观后感——时代
    Android6.0动态获取权限
    Androidannotations框架
    Android屏幕适配笔记
    Android 网络状态检测
    氢氘交换
    springboot datajpa 简明说明
    算法学习
  • 原文地址:https://www.cnblogs.com/heyang78/p/12600888.html
Copyright © 2011-2022 走看看