需求:输入的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日--